home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2009 March / ME_03_2009.iso / Software / Internet / Firefox 3.0.8.dmg / Firefox.app / Contents / MacOS / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2009-03-26  |  106.4 KB  |  3,230 lines

  1. //@line 44 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_IDLETIME            = "app.update.idletime";
  10. const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
  11. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  12. const PREF_APP_UPDATE_URL                 = "app.update.url";
  13. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  14. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  15. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  16. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  17. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  18. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  19. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  20. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never.";
  21. const PREF_PARTNER_BRANCH                 = "app.partner.";
  22. const PREF_APP_DISTRIBUTION               = "distribution.id";
  23. const PREF_APP_DISTRIBUTION_VERSION       = "distribution.version";
  24.  
  25. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  26. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  27. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  28. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  29. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  30.  
  31. const KEY_GREDIR          = "GreD";
  32. const KEY_APPDIR          = "XCurProcD";
  33. //@line 79 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  34.  
  35. const DIR_UPDATES         = "updates";
  36. const FILE_UPDATE_STATUS  = "update.status";
  37. const FILE_UPDATE_ARCHIVE = "update.mar";
  38. const FILE_UPDATE_LOG     = "update.log"
  39. const FILE_UPDATES_DB     = "updates.xml";
  40. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  41. const FILE_PERMS_TEST     = "update.test";
  42. const FILE_LAST_LOG       = "last-update.log";
  43. const FILE_UPDATER_INI    = "updater.ini";
  44.  
  45. const MODE_RDONLY   = 0x01;
  46. const MODE_WRONLY   = 0x02;
  47. const MODE_CREATE   = 0x08;
  48. const MODE_APPEND   = 0x10;
  49. const MODE_TRUNCATE = 0x20;
  50.  
  51. const PERMS_FILE      = 0644;
  52. const PERMS_DIRECTORY = 0755;
  53.  
  54. const STATE_NONE            = "null";
  55. const STATE_DOWNLOADING     = "downloading";
  56. const STATE_PENDING         = "pending";
  57. const STATE_APPLYING        = "applying";
  58. const STATE_SUCCEEDED       = "succeeded";
  59. const STATE_DOWNLOAD_FAILED = "download-failed";
  60. const STATE_FAILED          = "failed";
  61.  
  62. // From updater/errors.h:
  63. const WRITE_ERROR = 7;
  64.  
  65. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  66. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  67. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  68.  
  69. const TOOLKIT_ID              = "toolkit@mozilla.org";
  70.  
  71. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  72.  
  73. const nsIExtensionManager     = Components.interfaces.nsIExtensionManager;
  74. const nsILocalFile            = Components.interfaces.nsILocalFile;
  75. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  76. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  77. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  78. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  79. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  80. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  81. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  82. const nsIINIParserFactory     = Components.interfaces.nsIINIParserFactory;
  83.  
  84. const Node = Components.interfaces.nsIDOMNode;
  85.  
  86. var gApp        = null;
  87. var gPref       = null;
  88. var gABI        = null;
  89. var gOSVersion  = null;
  90. var gLocale     = null;
  91. var gConsole    = null;
  92. var gLogEnabled = { };
  93.  
  94. // shared code for suppressing bad cert dialogs
  95. //@line 40 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/shared/src/badCertHandler.js"
  96.  
  97. /**
  98.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  99.  */
  100. function checkCert(channel) {
  101.   if (!channel.originalURI.schemeIs("https"))  // bypass
  102.     return;
  103.  
  104.   const Ci = Components.interfaces;  
  105.   var cert =
  106.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  107.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  108.  
  109.   var issuer = cert.issuer;
  110.   while (issuer && !cert.equals(issuer)) {
  111.     cert = issuer;
  112.     issuer = cert.issuer;
  113.   }
  114.  
  115.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  116.     throw "cert issuer is not built-in";
  117. }
  118.  
  119. /**
  120.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  121.  * security dialogs from being shown to the user.  It is better to simply fail
  122.  * if the certificate is bad. See bug 304286.
  123.  */
  124. function BadCertHandler() {
  125. }
  126. BadCertHandler.prototype = {
  127.  
  128.   // nsIChannelEventSink
  129.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  130.     // make sure the certificate of the old channel checks out before we follow
  131.     // a redirect from it.  See bug 340198.
  132.     checkCert(oldChannel);
  133.   },
  134.  
  135.   // Suppress any certificate errors
  136.   notifyCertProblem: function(socketInfo, status, targetSite) {
  137.     return true;
  138.   },
  139.  
  140.   // Suppress any ssl errors
  141.   notifySSLError: function(socketInfo, error, targetSite) {
  142.     return true;
  143.   },
  144.  
  145.   // nsIInterfaceRequestor
  146.   getInterface: function(iid) {
  147.     return this.QueryInterface(iid);
  148.   },
  149.  
  150.   // nsISupports
  151.   QueryInterface: function(iid) {
  152.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  153.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  154.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  155.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  156.         !iid.equals(Components.interfaces.nsISupports))
  157.       throw Components.results.NS_ERROR_NO_INTERFACE;
  158.     return this;
  159.   }
  160. };
  161. //@line 141 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  162.  
  163. /**
  164.  * Logs a string to the error console.
  165.  * @param   string
  166.  *          The string to write to the error console..
  167.  */
  168. function LOG(module, string) {
  169.   if (module in gLogEnabled || "all" in gLogEnabled) {
  170.     dump("*** " + module + ": " + string + "\n");
  171.     gConsole.logStringMessage(string);
  172.   }
  173. }
  174.  
  175. /**
  176.  * Convert a string containing binary values to hex.
  177.  */
  178. function binaryToHex(input) {
  179.   var result = "";
  180.   for (var i = 0; i < input.length; ++i) {
  181.     var hex = input.charCodeAt(i).toString(16);
  182.     if (hex.length == 1)
  183.       hex = "0" + hex;
  184.     result += hex;
  185.   }
  186.   return result;
  187. }
  188.  
  189. /**
  190.  * Gets a File URL spec for a nsIFile
  191.  * @param   file
  192.  *          The file to get a file URL spec to
  193.  * @returns The file URL spec to the file
  194.  */
  195. function getURLSpecFromFile(file) {
  196.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  197.                          .getService(Components.interfaces.nsIIOService);
  198.   var fph = ioServ.getProtocolHandler("file")
  199.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  200.   return fph.getURLSpecFromFile(file);
  201. }
  202.  
  203. /**
  204.  * Gets the specified directory at the specified hierarchy under a
  205.  * Directory Service key.
  206.  * @param   key
  207.  *          The Directory Service Key to start from
  208.  * @param   pathArray
  209.  *          An array of path components to locate beneath the directory
  210.  *          specified by |key|
  211.  * @return  nsIFile object for the location specified. If the directory
  212.  *          requested does not exist, it is created, along with any
  213.  *          parent directories that need to be created.
  214.  */
  215. function getDir(key, pathArray) {
  216.   return getDirInternal(key, pathArray, true, false);
  217. }
  218.  
  219. /**
  220.  * Gets the specified directory at the specified hierarchy under a
  221.  * Directory Service key.
  222.  * @param   key
  223.  *          The Directory Service Key to start from
  224.  * @param   pathArray
  225.  *          An array of path components to locate beneath the directory
  226.  *          specified by |key|
  227.  * @return  nsIFile object for the location specified. If the directory
  228.  *          requested does not exist, it is NOT created.
  229.  */
  230. function getDirNoCreate(key, pathArray) {
  231.   return getDirInternal(key, pathArray, false, false);
  232. }
  233.  
  234. /**
  235.  * Gets the specified directory at the specified hierarchy under the
  236.  * update root directory.
  237.  * @param   pathArray
  238.  *          An array of path components to locate beneath the directory
  239.  *          specified by |key|
  240.  * @return  nsIFile object for the location specified. If the directory
  241.  *          requested does not exist, it is created, along with any
  242.  *          parent directories that need to be created.
  243.  */
  244. function getUpdateDir(pathArray) {
  245.   return getDirInternal(KEY_APPDIR, pathArray, true, true);
  246. }
  247.  
  248. /**
  249.  * Gets the specified directory at the specified hierarchy under a
  250.  * Directory Service key.
  251.  * @param   key
  252.  *          The Directory Service Key to start from
  253.  * @param   pathArray
  254.  *          An array of path components to locate beneath the directory
  255.  *          specified by |key|
  256.  * @param   shouldCreate
  257.  *          true if the directory hierarchy specified in |pathArray|
  258.  *          should be created if it does not exist,
  259.  *          false otherwise.
  260.  * @param   update
  261.  *          true if finding the update directory,
  262.  *          false otherwise.
  263.  * @return  nsIFile object for the location specified.
  264.  */
  265. function getDirInternal(key, pathArray, shouldCreate, update) {
  266.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  267.                               .getService(Components.interfaces.nsIProperties);
  268.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  269. //@line 256 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  270.   for (var i = 0; i < pathArray.length; ++i) {
  271.     dir.append(pathArray[i]);
  272.     if (shouldCreate && !dir.exists())
  273.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  274.   }
  275.   return dir;
  276. }
  277.  
  278. /**
  279.  * Gets the file at the specified hierarchy under a Directory Service key.
  280.  * @param   key
  281.  *          The Directory Service Key to start from
  282.  * @param   pathArray
  283.  *          An array of path components to locate beneath the directory
  284.  *          specified by |key|. The last item in this array must be the
  285.  *          leaf name of a file.
  286.  * @return  nsIFile object for the file specified. The file is NOT created
  287.  *          if it does not exist, however all required directories along
  288.  *          the way are.
  289.  */
  290. function getFile(key, pathArray) {
  291.   var file = getDir(key, pathArray.slice(0, -1));
  292.   file.append(pathArray[pathArray.length - 1]);
  293.   return file;
  294. }
  295.  
  296. /**
  297.  * Gets the file at the specified hierarchy under the update root directory.
  298.  * @param   pathArray
  299.  *          An array of path components to locate beneath the directory
  300.  *          specified by |key|. The last item in this array must be the
  301.  *          leaf name of a file.
  302.  * @return  nsIFile object for the file specified. The file is NOT created
  303.  *          if it does not exist, however all required directories along
  304.  *          the way are.
  305.  */
  306. function getUpdateFile(pathArray) {
  307.   var file = getUpdateDir(pathArray.slice(0, -1));
  308.   file.append(pathArray[pathArray.length - 1]);
  309.   return file;
  310. }
  311.  
  312. /**
  313.  * Closes a Safe Output Stream
  314.  * @param   fos
  315.  *          The Safe Output Stream to close
  316.  */
  317. function closeSafeOutputStream(fos) {
  318.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  319.     try {
  320.       fos.finish();
  321.     }
  322.     catch (e) {
  323.       fos.close();
  324.     }
  325.   }
  326.   else
  327.     fos.close();
  328. }
  329.  
  330. /**
  331.  * Returns human readable status text from the updates.properties bundle
  332.  * based on an error code
  333.  * @param   code
  334.  *          The error code to look up human readable status text for
  335.  * @param   defaultCode
  336.  *          The default code to look up should human readable status text
  337.  *          not exist for |code|
  338.  * @returns A human readable status text string
  339.  */
  340. function getStatusTextFromCode(code, defaultCode) {
  341.   var sbs =
  342.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  343.       getService(Components.interfaces.nsIStringBundleService);
  344.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  345.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  346.   try {
  347.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  348.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  349.   }
  350.   catch (e) {
  351.     // Use the default reason
  352.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  353.   }
  354.   return reason;
  355. }
  356.  
  357. /**
  358.  * Get the Active Updates directory
  359.  * @param   key
  360.  *          The Directory Service Key (optional).
  361.  *          If used, don't search local appdata on Win32 and don't create dir.
  362.  * @returns The active updates directory, as a nsIFile object
  363.  */
  364. function getUpdatesDir(key) {
  365.   // Right now, we only support downloading one patch at a time, so we always
  366.   // use the same target directory.
  367.   var fileLocator =
  368.       Components.classes["@mozilla.org/file/directory_service;1"].
  369.       getService(Components.interfaces.nsIProperties);
  370.   var appDir;
  371.   if (key)
  372.     appDir = fileLocator.get(key, Components.interfaces.nsIFile);
  373.   else {
  374.     appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  375. //@line 367 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  376.   }
  377.   appDir.append(DIR_UPDATES);
  378.   appDir.append("0");
  379.   if (!appDir.exists() && !key)
  380.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  381.   return appDir;
  382. }
  383.  
  384. /**
  385.  * Reads the update state from the update.status file in the specified
  386.  * directory.
  387.  * @param   dir
  388.  *          The dir to look for an update.status file in
  389.  * @returns The status value of the update.
  390.  */
  391. function readStatusFile(dir) {
  392.   var statusFile = dir.clone();
  393.   statusFile.append(FILE_UPDATE_STATUS);
  394.   LOG("General", "Reading Status File: " + statusFile.path);
  395.   return readStringFromFile(statusFile) || STATE_NONE;
  396. }
  397.  
  398. /**
  399.  * Writes the current update operation/state to a file in the patch
  400.  * directory, indicating to the patching system that operations need
  401.  * to be performed.
  402.  * @param   dir
  403.  *          The patch directory where the update.status file should be
  404.  *          written.
  405.  * @param   state
  406.  *          The state value to write.
  407.  */
  408. function writeStatusFile(dir, state) {
  409.   var statusFile = dir.clone();
  410.   statusFile.append(FILE_UPDATE_STATUS);
  411.   writeStringToFile(statusFile, state);
  412. }
  413.  
  414. /**
  415.  * Removes the Updates Directory
  416.  * @param   key
  417.  *          The Directory Service Key under which update directory resides
  418.  *          (optional).
  419.  */
  420. function cleanUpUpdatesDir(key) {
  421.   // Bail out if we don't have appropriate permissions
  422.   var updateDir;
  423.   try {
  424.     updateDir = getUpdatesDir(key);
  425.   }
  426.   catch (e) {
  427.     return;
  428.   }
  429.  
  430.   var e = updateDir.directoryEntries;
  431.   while (e.hasMoreElements()) {
  432.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  433.     // Preserve the last update log file for debugging purposes
  434.     if (f.leafName == FILE_UPDATE_LOG) {
  435.       try {
  436.         var dir = f.parent.parent;
  437.         var logFile = dir.clone();
  438.         logFile.append(FILE_LAST_LOG);
  439.         if (logFile.exists())
  440.           logFile.remove(false);
  441.         f.copyTo(dir, FILE_LAST_LOG);
  442.       }
  443.       catch (e) {
  444.         LOG("General", "Failed to copy file: " + f.path);
  445.       }
  446.     }
  447.     // Now, recursively remove this file.  The recusive removal is really
  448.     // only needed on Mac OSX because this directory will contain a copy of
  449.     // updater.app, which is itself a directory.
  450.     try {
  451.       f.remove(true);
  452.     }
  453.     catch (e) {
  454.       LOG("General", "Failed to remove file: " + f.path);
  455.     }
  456.   }
  457.   try {
  458.     updateDir.remove(false);
  459.   } catch (e) {
  460.     LOG("General", "Failed to remove update directory: " + updateDir.path +
  461.         " - This is almost always bad. Exception = " + e);
  462.     throw e;
  463.   }
  464. }
  465.  
  466. /**
  467.  * Clean up updates list and the updates directory.
  468.  * @param   key
  469.  *          The Directory Service Key under which update directory resides
  470.  *          (optional).
  471.  */
  472. function cleanupActiveUpdate(key) {
  473.   // Move the update from the Active Update list into the Past Updates list.
  474.   var um =
  475.       Components.classes["@mozilla.org/updates/update-manager;1"].
  476.       getService(Components.interfaces.nsIUpdateManager);
  477.   um.activeUpdate = null;
  478.   um.saveUpdates();
  479.  
  480.   // Now trash the updates directory, since we're done with it
  481.   cleanUpUpdatesDir(key);
  482. }
  483.  
  484. /**
  485.  * Gets a preference value, handling the case where there is no default.
  486.  * @param   func
  487.  *          The name of the preference function to call, on nsIPrefBranch
  488.  * @param   preference
  489.  *          The name of the preference
  490.  * @param   defaultValue
  491.  *          The default value to return in the event the preference has
  492.  *          no setting
  493.  * @returns The value of the preference, or undefined if there was no
  494.  *          user or default value.
  495.  */
  496. function getPref(func, preference, defaultValue) {
  497.   try {
  498.     return gPref[func](preference);
  499.   }
  500.   catch (e) {
  501.   }
  502.   return defaultValue;
  503. }
  504.  
  505. /**
  506.  * Gets the locale specified by the 'Locale' key in the 'Installation' section
  507.  * of updater.ini if it is available. Otherwise the general.useragent.locale
  508.  * preference is used to get the locale. It's possible for this preference to
  509.  * be localized, so we have to do a little extra work here. Similar code
  510.  * exists in nsHttpHandler.cpp when building the UA string.
  511.  */
  512. function getLocale() {
  513.   if (gLocale)
  514.     return gLocale;
  515.  
  516.   try {
  517. //@line 509 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  518.     var updaterIni = getFile(KEY_GREDIR, ["updater.app", "Contents", "MacOS",
  519.                                           FILE_UPDATER_INI]);
  520. //@line 514 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  521.     var iniParser = Components.classes["@mozilla.org/xpcom/ini-parser-factory;1"]
  522.                               .getService(nsIINIParserFactory).createINIParser(updaterIni);
  523.     gLocale = iniParser.getString("Installation", "Locale");
  524.     LOG("General", "Getting Locale from File: " + updaterIni.path + " Locale: " + gLocale);
  525.     return gLocale;
  526.   } catch (e) {}
  527.  
  528.   try {
  529.     // Get the default branch
  530.     var prefs = Components.classes["@mozilla.org/preferences-service;1"]
  531.         .getService(Components.interfaces.nsIPrefService);
  532.     var defaultPrefs = prefs.getDefaultBranch(null);
  533.     gLocale = defaultPrefs.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  534.   } catch (e) {
  535.     gLocale = gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  536.   }
  537.  
  538.   return gLocale;
  539. }
  540.  
  541. /**
  542.  * Read the update channel from defaults only.  We do this to ensure that
  543.  * the channel is tightly coupled with the application and does not apply
  544.  * to other instances of the application that may use the same profile.
  545.  */
  546. function getUpdateChannel() {
  547.   var channel = "default";
  548.   var prefName;
  549.   var prefValue;
  550.  
  551.   var defaults =
  552.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  553.       getDefaultBranch(null);
  554.   try {
  555.     channel = defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  556.   } catch (e) {
  557.     // use default when pref not found
  558.   }
  559.  
  560.   try {
  561.     var partners = gPref.getChildList(PREF_PARTNER_BRANCH, { });
  562.     if (partners.length) {
  563.       channel += "-cck";
  564.       partners.sort();
  565.  
  566.       for each (prefName in partners) {
  567.         prefValue = gPref.getCharPref(prefName);
  568.         channel += "-" + prefValue;
  569.       }
  570.     }
  571.   }
  572.   catch (e) {
  573.     Components.utils.reportError(e);
  574.   }
  575.  
  576.   return channel;
  577. }
  578.  
  579. /* Get the distribution pref values, from defaults only */
  580. function getDistributionPrefValue(aPrefName) {
  581.   var prefValue = "default";
  582.  
  583.   var defaults =
  584.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  585.       getDefaultBranch(null);
  586.   try {
  587.     prefValue = defaults.getCharPref(aPrefName);
  588.   } catch (e) {
  589.     // use default when pref not found
  590.   }
  591.  
  592.   return prefValue;
  593. }
  594.  
  595. /**
  596.  * An enumeration of items in a JS array.
  597.  * @constructor
  598.  */
  599. function ArrayEnumerator(aItems) {
  600.   this._index = 0;
  601.   if (aItems) {
  602.     for (var i = 0; i < aItems.length; ++i) {
  603.       if (!aItems[i])
  604.         aItems.splice(i, 1);
  605.     }
  606.   }
  607.   this._contents = aItems;
  608. }
  609.  
  610. ArrayEnumerator.prototype = {
  611.   _index: 0,
  612.   _contents: [],
  613.  
  614.   hasMoreElements: function() {
  615.     return this._index < this._contents.length;
  616.   },
  617.  
  618.   getNext: function() {
  619.     return this._contents[this._index++];
  620.   }
  621. };
  622.  
  623. /**
  624.  * Trims a prefix from a string.
  625.  * @param   string
  626.  *          The source string
  627.  * @param   prefix
  628.  *          The prefix to remove.
  629.  * @returns The suffix (string - prefix)
  630.  */
  631. function stripPrefix(string, prefix) {
  632.   return string.substr(prefix.length);
  633. }
  634.  
  635. /**
  636.  * Writes a string of text to a file.  A newline will be appended to the data
  637.  * written to the file.  This function only works with ASCII text.
  638.  */
  639. function writeStringToFile(file, text) {
  640.   var fos =
  641.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  642.       createInstance(nsIFileOutputStream);
  643.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  644.   if (!file.exists())
  645.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  646.   fos.init(file, modeFlags, PERMS_FILE, 0);
  647.   text += "\n";
  648.   fos.write(text, text.length);
  649.   closeSafeOutputStream(fos);
  650. }
  651.  
  652. /**
  653.  * Reads a string of text from a file.  A trailing newline will be removed
  654.  * before the result is returned.  This function only works with ASCII text.
  655.  */
  656. function readStringFromFile(file) {
  657.   var fis =
  658.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  659.       createInstance(nsIFileInputStream);
  660.   var modeFlags = MODE_RDONLY;
  661.   if (!file.exists())
  662.     return null;
  663.   fis.init(file, modeFlags, PERMS_FILE, 0);
  664.   var sis =
  665.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  666.       createInstance(Components.interfaces.nsIScriptableInputStream);
  667.   sis.init(fis);
  668.   var text = sis.read(sis.available());
  669.   sis.close();
  670.   if (text[text.length - 1] == "\n")
  671.     text = text.slice(0, -1);
  672.   return text;
  673. }
  674.  
  675. function getObserverService()
  676. {
  677.   return Components.classes["@mozilla.org/observer-service;1"]
  678.                    .getService(Components.interfaces.nsIObserverService);
  679. }
  680.  
  681. /**
  682.  * Update Patch
  683.  * @param   patch
  684.  *          A <patch> element to initialize this object with
  685.  * @throws if patch has a size of 0
  686.  * @constructor
  687.  */
  688. function UpdatePatch(patch) {
  689.   this._properties = {};
  690.   for (var i = 0; i < patch.attributes.length; ++i) {
  691.     var attr = patch.attributes.item(i);
  692.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  693.     switch (attr.name) {
  694.     case "selected":
  695.       this.selected = attr.value == "true";
  696.       break;
  697.     case "size":
  698.       if (0 == parseInt(attr.value)) {
  699.         LOG("UpdatePatch", "0-sized patch!");
  700.         throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  701.       }
  702.       // fall through
  703.     default:
  704.       this[attr.name] = attr.value;
  705.       break;
  706.     };
  707.   }
  708. }
  709. UpdatePatch.prototype = {
  710.   /**
  711.    * See nsIUpdateService.idl
  712.    */
  713.   serialize: function(updates) {
  714.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  715.     patch.setAttribute("type", this.type);
  716.     patch.setAttribute("URL", this.URL);
  717.     patch.setAttribute("hashFunction", this.hashFunction);
  718.     patch.setAttribute("hashValue", this.hashValue);
  719.     patch.setAttribute("size", this.size);
  720.     patch.setAttribute("selected", this.selected);
  721.     patch.setAttribute("state", this.state);
  722.  
  723.     for (var p in this._properties) {
  724.       if (this._properties[p].present)
  725.         patch.setAttribute(p, this._properties[p].data);
  726.     }
  727.  
  728.     return patch;
  729.   },
  730.  
  731.   /**
  732.    * A hash of custom properties
  733.    */
  734.   _properties: null,
  735.  
  736.   /**
  737.    * See nsIWritablePropertyBag.idl
  738.    */
  739.   setProperty: function(name, value) {
  740.     this._properties[name] = { data: value, present: true };
  741.   },
  742.  
  743.   /**
  744.    * See nsIWritablePropertyBag.idl
  745.    */
  746.   deleteProperty: function(name) {
  747.     if (name in this._properties)
  748.       this._properties[name].present = false;
  749.     else
  750.       throw Components.results.NS_ERROR_FAILURE;
  751.   },
  752.  
  753.   /**
  754.    * See nsIPropertyBag.idl
  755.    */
  756.   get enumerator() {
  757.     var properties = [];
  758.     for (var p in this._properties)
  759.       properties.push(this._properties[p].data);
  760.     return new ArrayEnumerator(properties);
  761.   },
  762.  
  763.   /**
  764.    * See nsIPropertyBag.idl
  765.    */
  766.   getProperty: function(name) {
  767.     if (name in this._properties &&
  768.         this._properties[name].present)
  769.       return this._properties[name].data;
  770.     throw Components.results.NS_ERROR_FAILURE;
  771.   },
  772.  
  773.   /**
  774.    * Returns whether or not the update.status file for this patch exists at the
  775.    * appropriate location.
  776.    */
  777.   get statusFileExists() {
  778.     var statusFile = getUpdatesDir();
  779.     statusFile.append(FILE_UPDATE_STATUS);
  780.     return statusFile.exists();
  781.   },
  782.  
  783.   /**
  784.    * See nsIUpdateService.idl
  785.    */
  786.   get state() {
  787.     if (!this.statusFileExists)
  788.       return STATE_NONE;
  789.     return this._properties.state;
  790.   },
  791.   set state(val) {
  792.     this._properties.state = val;
  793.   },
  794.  
  795.   /**
  796.    * See nsISupports.idl
  797.    */
  798.   QueryInterface: function(iid) {
  799.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  800.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  801.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  802.         !iid.equals(Components.interfaces.nsISupports))
  803.       throw Components.results.NS_ERROR_NO_INTERFACE;
  804.     return this;
  805.   }
  806. };
  807.  
  808. /**
  809.  * Update
  810.  * Implements nsIUpdate
  811.  * @param   update
  812.  *          An <update> element to initialize this object with
  813.  * @throws if the update contains no patches
  814.  * @constructor
  815.  */
  816. function Update(update) {
  817.   this._properties = {};
  818.   this._patches = [];
  819.   this.installDate = 0;
  820.   this.isCompleteUpdate = false;
  821.   this.channel = "default"
  822.  
  823.   // Null <update>, assume this is a message container and do no
  824.   // further initialization
  825.   if (!update)
  826.     return;
  827.  
  828.   for (var i = 0; i < update.childNodes.length; ++i) {
  829.     var patchElement = update.childNodes.item(i);
  830.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  831.         patchElement.localName != "patch")
  832.       continue;
  833.  
  834.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  835.     try {
  836.       var patch = new UpdatePatch(patchElement);
  837.     } catch (e) {
  838.       continue;
  839.     }
  840.     this._patches.push(patch);
  841.   }
  842.  
  843.   if (0 == this._patches.length)
  844.     throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  845.  
  846.   for (var i = 0; i < update.attributes.length; ++i) {
  847.     var attr = update.attributes.item(i);
  848.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  849.     if (attr.name == "installDate" && attr.value)
  850.       this.installDate = parseInt(attr.value);
  851.     else if (attr.name == "isCompleteUpdate")
  852.       this.isCompleteUpdate = attr.value == "true";
  853.     else if (attr.name == "isSecurityUpdate")
  854.       this.isSecurityUpdate = attr.value == "true";
  855.     else if (attr.name == "detailsURL")
  856.       this._detailsURL = attr.value;
  857.     else if (attr.name == "channel")
  858.       this.channel = attr.value;
  859.     else
  860.       this[attr.name] = attr.value;
  861.   }
  862.  
  863.   // The Update Name is either the string provided by the <update> element, or
  864.   // the string: "<App Name> <Update App Version>"
  865.   var name = "";
  866.   if (update.hasAttribute("name"))
  867.     name = update.getAttribute("name");
  868.   else {
  869.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  870.                         .getService(Components.interfaces.nsIStringBundleService);
  871.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  872.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  873.     var appName = brandBundle.GetStringFromName("brandShortName");
  874.     name = updateBundle.formatStringFromName("updateName",
  875.                                              [appName, this.version], 2);
  876.   }
  877.   this.name = name;
  878. }
  879. Update.prototype = {
  880.   /**
  881.    * See nsIUpdateService.idl
  882.    */
  883.   get patchCount() {
  884.     return this._patches.length;
  885.   },
  886.  
  887.   /**
  888.    * See nsIUpdateService.idl
  889.    */
  890.   getPatchAt: function(index) {
  891.     return this._patches[index];
  892.   },
  893.  
  894.   /**
  895.    * See nsIUpdateService.idl
  896.    *
  897.    * We use a copy of the state cached on this object in |_state| only when
  898.    * there is no selected patch, i.e. in the case when we could not load
  899.    * |.activeUpdate| from the update manager for some reason but still have
  900.    * the update.status file to work with.
  901.    */
  902.   _state: "",
  903.   set state(state) {
  904.     if (this.selectedPatch)
  905.       this.selectedPatch.state = state;
  906.     this._state = state;
  907.     return state;
  908.   },
  909.   get state() {
  910.     if (this.selectedPatch)
  911.       return this.selectedPatch.state;
  912.     return this._state;
  913.   },
  914.  
  915.   /**
  916.    * See nsIUpdateService.idl
  917.    */
  918.   errorCode: 0,
  919.  
  920.   /**
  921.    * See nsIUpdateService.idl
  922.    */
  923.   get selectedPatch() {
  924.     for (var i = 0; i < this.patchCount; ++i) {
  925.       if (this._patches[i].selected)
  926.         return this._patches[i];
  927.     }
  928.     return null;
  929.   },
  930.  
  931.   /**
  932.    * See nsIUpdateService.idl
  933.    */
  934.   get detailsURL() {
  935.     if (!this._detailsURL) {
  936.       try {
  937.         // Try using a default details URL supplied by the distribution
  938.         // if the update XML does not supply one.
  939.         var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  940.                                   .getService(Components.interfaces.nsIURLFormatter);
  941.         return formatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
  942.       }
  943.       catch (e) {
  944.       }
  945.     }
  946.     return this._detailsURL || "";
  947.   },
  948.  
  949.   /**
  950.    * See nsIUpdateService.idl
  951.    */
  952.   serialize: function(updates) {
  953.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  954.     update.setAttribute("type", this.type);
  955.     update.setAttribute("name", this.name);
  956.     update.setAttribute("version", this.version);
  957.     update.setAttribute("platformVersion", this.platformVersion);
  958.     update.setAttribute("extensionVersion", this.extensionVersion);
  959.     update.setAttribute("detailsURL", this.detailsURL);
  960.     update.setAttribute("licenseURL", this.licenseURL);
  961.     update.setAttribute("serviceURL", this.serviceURL);
  962.     update.setAttribute("installDate", this.installDate);
  963.     update.setAttribute("statusText", this.statusText);
  964.     update.setAttribute("buildID", this.buildID);
  965.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  966.     update.setAttribute("channel", this.channel);
  967.     updates.documentElement.appendChild(update);
  968.  
  969.     for (var p in this._properties) {
  970.       if (this._properties[p].present)
  971.         update.setAttribute(p, this._properties[p].data);
  972.     }
  973.  
  974.     for (var i = 0; i < this.patchCount; ++i)
  975.       update.appendChild(this.getPatchAt(i).serialize(updates));
  976.  
  977.     return update;
  978.   },
  979.  
  980.   /**
  981.    * A hash of custom properties
  982.    */
  983.   _properties: null,
  984.  
  985.   /**
  986.    * See nsIWritablePropertyBag.idl
  987.    */
  988.   setProperty: function(name, value) {
  989.     this._properties[name] = { data: value, present: true };
  990.   },
  991.  
  992.   /**
  993.    * See nsIWritablePropertyBag.idl
  994.    */
  995.   deleteProperty: function(name) {
  996.     if (name in this._properties)
  997.       this._properties[name].present = false;
  998.     else
  999.       throw Components.results.NS_ERROR_FAILURE;
  1000.   },
  1001.  
  1002.   /**
  1003.    * See nsIPropertyBag.idl
  1004.    */
  1005.   get enumerator() {
  1006.     var properties = [];
  1007.     for (var p in this._properties)
  1008.       properties.push(this._properties[p].data);
  1009.     return new ArrayEnumerator(properties);
  1010.   },
  1011.  
  1012.   /**
  1013.    * See nsIPropertyBag.idl
  1014.    */
  1015.   getProperty: function(name) {
  1016.     if (name in this._properties &&
  1017.         this._properties[name].present)
  1018.       return this._properties[name].data;
  1019.     throw Components.results.NS_ERROR_FAILURE;
  1020.   },
  1021.  
  1022.   /**
  1023.    * See nsISupports.idl
  1024.    */
  1025.   QueryInterface: function(iid) {
  1026.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  1027.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  1028.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  1029.         !iid.equals(Components.interfaces.nsISupports))
  1030.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1031.     return this;
  1032.   }
  1033. };
  1034.  
  1035. /**
  1036.  * UpdateService
  1037.  * A Service for managing the discovery and installation of software updates.
  1038.  * @constructor
  1039.  */
  1040. function UpdateService() {
  1041.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  1042.                     .getService(Components.interfaces.nsIXULAppInfo)
  1043.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  1044.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  1045.                     .getService(Components.interfaces.nsIPrefBranch2);
  1046.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  1047.                        .getService(Components.interfaces.nsIConsoleService);
  1048.  
  1049.   // Not all builds have a known ABI
  1050.   try {
  1051.     gABI = gApp.XPCOMABI;
  1052.   }
  1053.   catch (e) {
  1054.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  1055.   }
  1056.  
  1057.   var osVersion;
  1058.   var sysInfo = Components.classes["@mozilla.org/system-info;1"]
  1059.                           .getService(Components.interfaces.nsIPropertyBag2);
  1060.   try {
  1061.     osVersion = sysInfo.getProperty("name") + " " + sysInfo.getProperty("version");
  1062.   }
  1063.   catch (e) {
  1064.     LOG("UpdateService", "OS Version unknown: updates are not possible.");
  1065.   }
  1066.  
  1067.   if (osVersion) {
  1068.     try {
  1069.       osVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
  1070.     }
  1071.     catch (e) {
  1072.       // Not all platforms have a secondary widget library, so an error is nothing to worry about.
  1073.     }
  1074.     gOSVersion = encodeURIComponent(osVersion);
  1075.   }
  1076.  
  1077. //@line 1071 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1078.   // Mac universal build should report a different ABI than either macppc
  1079.   // or mactel.
  1080.   var macutils = Components.classes["@mozilla.org/xpcom/mac-utils;1"]
  1081.                            .getService(Components.interfaces.nsIMacUtils);
  1082.  
  1083.   if (macutils.isUniversalBinary)
  1084.     gABI = "Universal-gcc3";
  1085. //@line 1079 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1086.  
  1087.   // Start the update timer only after a profile has been selected so that the
  1088.   // appropriate values for the update check are read from the user's profile.
  1089.   var os = getObserverService();
  1090.  
  1091.   os.addObserver(this, "profile-after-change", false);
  1092.  
  1093.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid
  1094.   // shutdown leaks.
  1095.   os.addObserver(this, "xpcom-shutdown", false);
  1096. }
  1097.  
  1098. UpdateService.prototype = {
  1099.   /**
  1100.    * The downloader we are using to download updates. There is only ever one of
  1101.    * these.
  1102.    */
  1103.   _downloader: null,
  1104.  
  1105.   /**
  1106.    * Handle Observer Service notifications
  1107.    * @param   subject
  1108.    *          The subject of the notification
  1109.    * @param   topic
  1110.    *          The notification name
  1111.    * @param   data
  1112.    *          Additional data
  1113.    */
  1114.   observe: function(subject, topic, data) {
  1115.     var os = getObserverService();
  1116.  
  1117.     switch (topic) {
  1118.     case "profile-after-change":
  1119.       os.removeObserver(this, "profile-after-change");
  1120.       this._start();
  1121.       break;
  1122.     case "xpcom-shutdown":
  1123.       os.removeObserver(this, "xpcom-shutdown");
  1124.  
  1125.       // Release Services
  1126.       gApp      = null;
  1127.       gPref     = null;
  1128.       gConsole  = null;
  1129.       break;
  1130.     }
  1131.   },
  1132.  
  1133.   /**
  1134.    * Start the Update Service
  1135.    */
  1136.   _start: function() {
  1137.     // Start logging
  1138.     this._initLoggingPrefs();
  1139.  
  1140.     // Clean up any extant updates
  1141.     this._postUpdateProcessing();
  1142.  
  1143.     // Register a background update check timer
  1144.     var tm =
  1145.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  1146.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  1147.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  1148.     tm.registerTimer("background-update-timer", this, interval);
  1149.  
  1150.     // Resume fetching...
  1151.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1152.                         .getService(Components.interfaces.nsIUpdateManager);
  1153.     var activeUpdate = um.activeUpdate;
  1154.     if (activeUpdate) {
  1155.       var status = this.downloadUpdate(activeUpdate, true);
  1156.       if (status == STATE_NONE)
  1157.         cleanupActiveUpdate();
  1158.     }
  1159.   },
  1160.  
  1161.   /**
  1162.    * Perform post-processing on updates lingering in the updates directory
  1163.    * from a previous browser session - either report install failures (and
  1164.    * optionally attempt to fetch a different version if appropriate) or
  1165.    * notify the user of install success.
  1166.    */
  1167.   _postUpdateProcessing: function() {
  1168.     // Detect installation failures and notify
  1169.  
  1170.     // Bail out if we don't have appropriate permissions
  1171.     if (!this.canUpdate)
  1172.       return;
  1173.  
  1174.     var status = readStatusFile(getUpdatesDir());
  1175.  
  1176.     // Make sure to cleanup after an update that failed for an unknown reason
  1177.     if (status == "null")
  1178.       status = null;
  1179.  
  1180.     var updRootKey = null;
  1181. //@line 1196 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1182.  
  1183.     if (status == STATE_DOWNLOADING) {
  1184.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  1185.     }
  1186.     else if (status != null) {
  1187.       // null status means the update.status file is not present, because either:
  1188.       // 1) no update was performed, and so there's no UI to show
  1189.       // 2) an update was attempted but failed during checking, transfer or
  1190.       //    verification, and was cleaned up at that point, and UI notifying of
  1191.       //    that error was shown at that stage.
  1192.       var um =
  1193.           Components.classes["@mozilla.org/updates/update-manager;1"].
  1194.           getService(Components.interfaces.nsIUpdateManager);
  1195.       var prompter =
  1196.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  1197.           createInstance(Components.interfaces.nsIUpdatePrompt);
  1198.  
  1199.       var shouldCleanup = true;
  1200.       var update = um.activeUpdate;
  1201.       if (!update) {
  1202.         update = new Update(null);
  1203.       }
  1204.       update.state = status;
  1205.       var sbs =
  1206.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  1207.           getService(Components.interfaces.nsIStringBundleService);
  1208.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1209.       if (status == STATE_SUCCEEDED) {
  1210.         update.statusText = bundle.GetStringFromName("installSuccess");
  1211.  
  1212.         // Dig through the update history to find the patch that was just
  1213.         // installed and update its metadata.
  1214.         for (var i = 0; i < um.updateCount; ++i) {
  1215.           var umUpdate = um.getUpdateAt(i);
  1216.           if (umUpdate && umUpdate.version == update.version &&
  1217.                           umUpdate.buildID == update.buildID) {
  1218.             umUpdate.statusText = update.statusText;
  1219.             break;
  1220.           }
  1221.         }
  1222.  
  1223.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  1224.         prompter.showUpdateInstalled(update);
  1225. //@line 1243 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1226.         // Perform platform-specific post-update processing.
  1227.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  1228.           Components.classes[POST_UPDATE_CONTRACTID].
  1229.               createInstance(Components.interfaces.nsIRunnable).run();
  1230.         }
  1231. //@line 1249 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1232.  
  1233.         // Done with this update. Clean it up.
  1234.         cleanupActiveUpdate(updRootKey);
  1235.       }
  1236.       else {
  1237.         // If we hit an error, then the error code will be included in the
  1238.         // status string following a colon.  If we had an I/O error, then we
  1239.         // assume that the patch is not invalid, and we restage the patch so
  1240.         // that it can be attempted again the next time we restart.
  1241.         var ary = status.split(": ");
  1242.         update.state = ary[0];
  1243.         if (update.state == STATE_FAILED && ary[1]) {
  1244.           update.errorCode = ary[1];
  1245.           if (update.errorCode == WRITE_ERROR) {
  1246.             prompter.showUpdateError(update);
  1247.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1248.             return;
  1249.           }
  1250.         }
  1251.  
  1252.         // Something went wrong with the patch application process.
  1253.         cleanupActiveUpdate();
  1254.  
  1255.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1256.         var oldType = update.selectedPatch ? update.selectedPatch.type
  1257.                                            : "complete";
  1258.         if (update.selectedPatch && oldType == "partial") {
  1259.           // Partial patch application failed, try downloading the complete
  1260.           // update in the background instead.
  1261.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " +
  1262.               "failed, downloading Complete Patch and maybe showing UI");
  1263.           var status = this.downloadUpdate(update, true);
  1264.           if (status == STATE_NONE)
  1265.             cleanupActiveUpdate();
  1266.         }
  1267.         else {
  1268.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " +
  1269.               "only patch failed. Showing error.");
  1270.         }
  1271.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1272.         update.setProperty("patchingFailed", oldType);
  1273.         prompter.showUpdateError(update);
  1274.       }
  1275.     }
  1276.     else {
  1277.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1278.     }
  1279.   },
  1280.  
  1281.   /**
  1282.    * Initialize Logging preferences, formatted like so:
  1283.    *  app.update.log.<moduleName> = <true|false>
  1284.    */
  1285.   _initLoggingPrefs: function() {
  1286.     try {
  1287.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1288.                         .getService(Components.interfaces.nsIPrefService);
  1289.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1290.       var modules = logBranch.getChildList("", { value: 0 });
  1291.  
  1292.       for (var i = 0; i < modules.length; ++i) {
  1293.         if (logBranch.prefHasUserValue(modules[i]))
  1294.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1295.       }
  1296.     }
  1297.     catch (e) {
  1298.     }
  1299.   },
  1300.  
  1301.   /**
  1302.    * Notified when a timer fires
  1303.    * @param   timer
  1304.    *          The timer that fired
  1305.    */
  1306.   notify: function(timer) {
  1307.     // If a download is in progress, then do nothing.
  1308.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1309.       return;
  1310.  
  1311.     var self = this;
  1312.     var listener = {
  1313.       /**
  1314.        * See nsIUpdateService.idl
  1315.        */
  1316.       onProgress: function(request, position, totalSize) {
  1317.       },
  1318.  
  1319.       /**
  1320.        * See nsIUpdateService.idl
  1321.        */
  1322.       onCheckComplete: function(request, updates, updateCount) {
  1323.         self._selectAndInstallUpdate(updates);
  1324.       },
  1325.  
  1326.       /**
  1327.        * See nsIUpdateService.idl
  1328.        */
  1329.       onError: function(request, update) {
  1330.         LOG("Checker", "Error during background update: " + update.statusText);
  1331.       },
  1332.     }
  1333.     this.backgroundChecker.checkForUpdates(listener, false);
  1334.   },
  1335.  
  1336.   /**
  1337.    * Determine whether or not an update requires user confirmation before it
  1338.    * can be installed.
  1339.    * @param   update
  1340.    *          The update to be installed
  1341.    * @returns true if a prompt UI should be shown asking the user if they want
  1342.    *          to install the update, false if the update should just be
  1343.    *          silently downloaded and installed.
  1344.    */
  1345.   _shouldPrompt: function(update) {
  1346.     // There are two possible outcomes here:
  1347.     // 1. download and install the update automatically
  1348.     // 2. alert the user about the presence of an update before doing anything
  1349.     //
  1350.     // The outcome we follow is determined as follows:
  1351.     //
  1352.     // Note:  all Major updates require notification and confirmation
  1353.     //
  1354.     // Update Type      Mode      Incompatible    Outcome
  1355.     // Major            0         Yes or No       Notify and Confirm
  1356.     // Major            1         No              Notify and Confirm
  1357.     // Major            1         Yes             Notify and Confirm
  1358.     // Major            2         Yes or No       Notify and Confirm
  1359.     // Minor            0         Yes or No       Auto Install
  1360.     // Minor            1         No              Auto Install
  1361.     // Minor            1         Yes             Notify and Confirm
  1362.     // Minor            2         No              Auto Install
  1363.     // Minor            2         Yes             Notify and Confirm
  1364.     //
  1365.     // In addition, if there is a license associated with an update, regardless
  1366.     // of type it must be agreed to.
  1367.     //
  1368.     // If app.update.enabled is set to false, an update check is not performed
  1369.     // at all, and so none of the decision making above is entered into.
  1370.     //
  1371.     if (update.type == "major") {
  1372.       LOG("Checker", "_shouldPrompt: Prompting because it is a major update");
  1373.       return true;
  1374.     }
  1375.  
  1376.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1377.     try {
  1378.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1379.     }
  1380.     catch (e) {
  1381.       licenseAccepted = false;
  1382.     }
  1383.  
  1384.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1385.     if (!updateEnabled) {
  1386.       LOG("Checker", "_shouldPrompt: Not prompting because update is " +
  1387.           "disabled");
  1388.       return false;
  1389.     }
  1390.  
  1391.     // User has turned off automatic download and install
  1392.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1393.     if (!autoEnabled) {
  1394.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1395.       return true;
  1396.     }
  1397.  
  1398.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1399.     case 1:
  1400.       // Mode 1 is do not prompt only if there are no incompatibilities
  1401.       // releases
  1402.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1403.       return !isCompatible(update);
  1404.     case 2:
  1405.       // Mode 2 is do not prompt only if there are no incompatibilities
  1406.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1407.       return !isCompatible(update);
  1408.     }
  1409.     // Mode 0 is do not prompt regardless of incompatibilities
  1410.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1411.         "ignore incompatibilities");
  1412.     return false;
  1413.   },
  1414.  
  1415.   /**
  1416.    * Determine which of the specified updates should be installed.
  1417.    * @param   updates
  1418.    *          An array of available updates
  1419.    */
  1420.   selectUpdate: function(updates) {
  1421.     if (updates.length == 0)
  1422.       return null;
  1423.  
  1424.     // Choose the newest of the available minor and major updates.
  1425.     var majorUpdate = null, minorUpdate = null;
  1426.     var newestMinor = updates[0], newestMajor = updates[0];
  1427.  
  1428.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1429.                        .getService(Components.interfaces.nsIVersionComparator);
  1430.     for (var i = 0; i < updates.length; ++i) {
  1431.       if (updates[i].type == "major" &&
  1432.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1433.         majorUpdate = newestMajor = updates[i];
  1434.       if (updates[i].type == "minor" &&
  1435.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1436.         minorUpdate = newestMinor = updates[i];
  1437.     }
  1438.  
  1439.     // IMPORTANT
  1440.     // If there's a minor update, always try and fetch that one first,
  1441.     // otherwise use the newest major update.
  1442.     // selectUpdate() only returns one update.
  1443.     // if major were to trump minor, and we said "never" to the major
  1444.     // we'd never get the minor update, since selectUpdate()
  1445.     // would return the major update that the user said "never" to
  1446.     // (shadowing the important minor update with security fixes)
  1447.     return minorUpdate || majorUpdate;
  1448.   },
  1449.  
  1450.   /**
  1451.    * Determine which of the specified updates should be installed and
  1452.    * begin the download/installation process, optionally prompting the
  1453.    * user for permission if required.
  1454.    * @param   updates
  1455.    *          An array of available updates
  1456.    */
  1457.   _selectAndInstallUpdate: function(updates) {
  1458.     // Don't prompt if there's an active update - the user is already
  1459.     // aware and is downloading, or performed some user action to prevent
  1460.     // notification.
  1461.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1462.                        .getService(Components.interfaces.nsIUpdateManager);
  1463.     if (um.activeUpdate)
  1464.       return;
  1465.  
  1466.     var update = this.selectUpdate(updates, updates.length);
  1467.     if (!update)
  1468.       return;
  1469.  
  1470.     // check if the user said "never" to this version
  1471.     // this check is done here, and not in selectUpdate() so that
  1472.     // the user can get an upgrade they said "never" to if they
  1473.     // manually do "Check for Updates..."
  1474.     // note, selectUpdate() only returns one update.
  1475.     // but in selectUpdate(), minor updates trump major updates
  1476.     // if major trumps minor, and we said "never" to the major
  1477.     // we'd never see the minor update.
  1478.     //
  1479.     // note, the never decision should only apply to major updates
  1480.     // see bug #350636 for a scenario where this could potentially
  1481.     // be an issue
  1482.     //
  1483.     // fix for bug #359093
  1484.     // version might one day come back from AUS as an
  1485.     // arbitrary (and possibly non ascii) string, so we need to encode it
  1486.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH + encodeURIComponent(update.version);
  1487.     var never = getPref("getBoolPref", neverPrefName, false);
  1488.     if (never && update.type == "major")
  1489.       return;
  1490.  
  1491.     if (this._shouldPrompt(update))
  1492.       showPromptIfNoIncompatibilities(update);
  1493.     else {
  1494.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1495.       var status = this.downloadUpdate(update, true);
  1496.       if (status == STATE_NONE)
  1497.         cleanupActiveUpdate();
  1498.     }
  1499.   },
  1500.  
  1501.   /**
  1502.    * The Checker used for background update checks.
  1503.    */
  1504.   _backgroundChecker: null,
  1505.  
  1506.   /**
  1507.    * See nsIUpdateService.idl
  1508.    */
  1509.   get backgroundChecker() {
  1510.     if (!this._backgroundChecker)
  1511.       this._backgroundChecker = new Checker();
  1512.     return this._backgroundChecker;
  1513.   },
  1514.  
  1515.   /**
  1516.    * See nsIUpdateService.idl
  1517.    */
  1518.   get canUpdate() {
  1519.     try {
  1520.       var appDirFile = getUpdateFile([FILE_PERMS_TEST]);
  1521.       LOG("UpdateService", "canUpdate?  testing " + appDirFile.path);
  1522.       if (!appDirFile.exists()) {
  1523.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1524.         appDirFile.remove(false);
  1525.       }
  1526.       var updateDir = getUpdatesDir();
  1527.       var upDirFile = updateDir.clone();
  1528.       upDirFile.append(FILE_PERMS_TEST);
  1529.       LOG("UpdateService", "canUpdate?  testing " + upDirFile.path);
  1530.       if (!upDirFile.exists()) {
  1531.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1532.         upDirFile.remove(false);
  1533.       }
  1534. //@line 1630 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1535.     }
  1536.     catch (e) {
  1537.        LOG("UpdateService", "can't update, no privileges: " + e);
  1538.       // No write privileges to install directory
  1539.       return false;
  1540.     }
  1541.     // If the administrator has locked the app update functionality
  1542.     // OFF - this is not just a user setting, so disable the manual
  1543.     // UI too.
  1544.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1545.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED)) {
  1546.       LOG("UpdateService", "can't update, disabled by pref");
  1547.       return false;
  1548.     }
  1549.  
  1550.     // If we don't know the binary platform we're updating, we can't update.
  1551.     if (!gABI) {
  1552.       LOG("UpdateService", "can't update, unknown ABI");
  1553.       return false;
  1554.     }
  1555.  
  1556.     // If we don't know the OS version we're updating, we can't update.
  1557.     if (!gOSVersion) {
  1558.       LOG("UpdateService", "can't update, unknown OS version");
  1559.       return false;
  1560.     }
  1561.  
  1562.     LOG("UpdateService", "can update");
  1563.     return true;
  1564.   },
  1565.  
  1566.   /**
  1567.    * See nsIUpdateService.idl
  1568.    */
  1569.   addDownloadListener: function(listener) {
  1570.     if (!this._downloader) {
  1571.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1572.       return;
  1573.     }
  1574.     this._downloader.addDownloadListener(listener);
  1575.   },
  1576.  
  1577.   /**
  1578.    * See nsIUpdateService.idl
  1579.    */
  1580.   removeDownloadListener: function(listener) {
  1581.     if (!this._downloader) {
  1582.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1583.       return;
  1584.     }
  1585.     this._downloader.removeDownloadListener(listener);
  1586.   },
  1587.  
  1588.   /**
  1589.    * See nsIUpdateService.idl
  1590.    */
  1591.   downloadUpdate: function(update, background) {
  1592.     if (!update)
  1593.       throw Components.results.NS_ERROR_NULL_POINTER;
  1594.     if (this.isDownloading) {
  1595.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1596.           background == this._downloader.background) {
  1597.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1598.         return readStatusFile(getUpdatesDir());
  1599.       }
  1600.       this._downloader.cancel();
  1601.     }
  1602.     this._downloader = new Downloader(background);
  1603.     return this._downloader.downloadUpdate(update);
  1604.   },
  1605.  
  1606.   /**
  1607.    * See nsIUpdateService.idl
  1608.    */
  1609.   pauseDownload: function() {
  1610.     if (this.isDownloading)
  1611.       this._downloader.cancel();
  1612.   },
  1613.  
  1614.   /**
  1615.    * See nsIUpdateService.idl
  1616.    */
  1617.   get isDownloading() {
  1618.     return this._downloader && this._downloader.isBusy;
  1619.   },
  1620.  
  1621.   /**
  1622.    * See nsISupports.idl
  1623.    */
  1624.   QueryInterface: function(iid) {
  1625.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1626.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  1627.         !iid.equals(Components.interfaces.nsIObserver) &&
  1628.         !iid.equals(Components.interfaces.nsISupports))
  1629.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1630.     return this;
  1631.   }
  1632. };
  1633.  
  1634. /**
  1635.  * A service to manage active and past updates.
  1636.  * @constructor
  1637.  */
  1638. function UpdateManager() {
  1639.   // Ensure the Active Update file is loaded
  1640.   var updates = this._loadXMLFileIntoArray(getUpdateFile([FILE_UPDATE_ACTIVE]));
  1641.   if (updates.length > 0)
  1642.     this._activeUpdate = updates[0];
  1643. }
  1644. UpdateManager.prototype = {
  1645.   /**
  1646.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1647.    * objects.
  1648.    */
  1649.   _updates: null,
  1650.  
  1651.   /**
  1652.    * The current actively downloading/installing update, as a nsIUpdate object.
  1653.    */
  1654.   _activeUpdate: null,
  1655.  
  1656.   /**
  1657.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1658.    * @param   file
  1659.    *          A nsIFile for the updates.xml file
  1660.    * @returns The array of nsIUpdate items held in the file.
  1661.    */
  1662.   _loadXMLFileIntoArray: function(file) {
  1663.     if (!file.exists()) {
  1664.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1665.       return [];
  1666.     }
  1667.  
  1668.     var result = [];
  1669.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1670.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1671.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1672.     try {
  1673.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1674.                             .createInstance(Components.interfaces.nsIDOMParser);
  1675.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1676.  
  1677.       var updateCount = doc.documentElement.childNodes.length;
  1678.       for (var i = 0; i < updateCount; ++i) {
  1679.         var updateElement = doc.documentElement.childNodes.item(i);
  1680.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1681.             updateElement.localName != "update")
  1682.           continue;
  1683.  
  1684.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1685.         try {
  1686.           var update = new Update(updateElement);
  1687.         } catch (e) {
  1688.           LOG("UpdateManager", "_loadXMLFileIntoArray: invalid update");
  1689.           continue;
  1690.         }
  1691.         result.push(new Update(updateElement));
  1692.       }
  1693.     }
  1694.     catch (e) {
  1695.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " +
  1696.           e);
  1697.     }
  1698.     fileStream.close();
  1699.     return result;
  1700.   },
  1701.  
  1702.   /**
  1703.    * Load the update manager, initializing state from state files.
  1704.    */
  1705.   _ensureUpdates: function() {
  1706.     if (!this._updates) {
  1707.       this._updates = this._loadXMLFileIntoArray(getUpdateFile(
  1708.                         [FILE_UPDATES_DB]));
  1709.  
  1710.       // Make sure that any active update is part of our updates list
  1711.       var active = this.activeUpdate;
  1712.       if (active)
  1713.         this._addUpdate(active);
  1714.     }
  1715.   },
  1716.  
  1717.   /**
  1718.    * See nsIUpdateService.idl
  1719.    */
  1720.   getUpdateAt: function(index) {
  1721.     this._ensureUpdates();
  1722.     return this._updates[index];
  1723.   },
  1724.  
  1725.   /**
  1726.    * See nsIUpdateService.idl
  1727.    */
  1728.   get updateCount() {
  1729.     this._ensureUpdates();
  1730.     return this._updates.length;
  1731.   },
  1732.  
  1733.   /**
  1734.    * See nsIUpdateService.idl
  1735.    */
  1736.   get activeUpdate() {
  1737.     if (this._activeUpdate &&
  1738.         this._activeUpdate.channel != getUpdateChannel()) {
  1739.       // User switched channels, clear out any old active updates and remove
  1740.       // partial downloads
  1741.       this._activeUpdate = null;
  1742.  
  1743.       // Destroy the updates directory, since we're done with it.
  1744.       cleanUpUpdatesDir();
  1745.     }
  1746.     return this._activeUpdate;
  1747.   },
  1748.   set activeUpdate(activeUpdate) {
  1749.     this._addUpdate(activeUpdate);
  1750.     this._activeUpdate = activeUpdate;
  1751.     if (!activeUpdate) {
  1752.       // If |activeUpdate| is null, we have updated both lists - the active list
  1753.       // and the history list, so we want to write both files.
  1754.       this.saveUpdates();
  1755.     }
  1756.     else
  1757.       this._writeUpdatesToXMLFile([this._activeUpdate],
  1758.                                   getUpdateFile([FILE_UPDATE_ACTIVE]));
  1759.     return activeUpdate;
  1760.   },
  1761.  
  1762.   /**
  1763.    * Add an update to the Updates list. If the item already exists in the list,
  1764.    * replace the existing value with the new value.
  1765.    * @param   update
  1766.    *          The nsIUpdate object to add.
  1767.    */
  1768.   _addUpdate: function(update) {
  1769.     if (!update)
  1770.       return;
  1771.     this._ensureUpdates();
  1772.     if (this._updates) {
  1773.       for (var i = 0; i < this._updates.length; ++i) {
  1774.         if (this._updates[i] &&
  1775.             this._updates[i].version == update.version &&
  1776.             this._updates[i].buildID == update.buildID) {
  1777.           // Replace the existing entry with the new value, updating
  1778.           // all metadata.
  1779.           this._updates[i] = update;
  1780.           return;
  1781.         }
  1782.       }
  1783.     }
  1784.     // Otherwise add it to the front of the list.
  1785.     if (update)
  1786.       this._updates = [update].concat(this._updates);
  1787.   },
  1788.  
  1789.   /**
  1790.    * Serializes an array of updates to an XML file
  1791.    * @param   updates
  1792.    *          An array of nsIUpdate objects
  1793.    * @param   file
  1794.    *          The nsIFile object to serialize to
  1795.    */
  1796.   _writeUpdatesToXMLFile: function(updates, file) {
  1797.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1798.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1799.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1800.     if (!file.exists())
  1801.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1802.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1803.  
  1804.     try {
  1805.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1806.                             .createInstance(Components.interfaces.nsIDOMParser);
  1807.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1808.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1809.  
  1810.       for (var i = 0; i < updates.length; ++i) {
  1811.         if (updates[i])
  1812.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1813.       }
  1814.  
  1815.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1816.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1817.       serializer.serializeToStream(doc.documentElement, fos, null);
  1818.     }
  1819.     catch (e) {
  1820.     }
  1821.  
  1822.     closeSafeOutputStream(fos);
  1823.   },
  1824.  
  1825.   /**
  1826.    * See nsIUpdateService.idl
  1827.    */
  1828.   saveUpdates: function() {
  1829.     this._writeUpdatesToXMLFile([this._activeUpdate],
  1830.                                 getUpdateFile([FILE_UPDATE_ACTIVE]));
  1831.     if (this._updates) {
  1832.       this._writeUpdatesToXMLFile(this._updates.slice(0, 10),
  1833.                                   getUpdateFile([FILE_UPDATES_DB]));
  1834.     }
  1835.   },
  1836.  
  1837.   /**
  1838.    * See nsISupports.idl
  1839.    */
  1840.   QueryInterface: function(iid) {
  1841.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1842.         !iid.equals(Components.interfaces.nsISupports))
  1843.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1844.     return this;
  1845.   }
  1846. };
  1847.  
  1848.  
  1849. /**
  1850.  * Checker
  1851.  * Checks for new Updates
  1852.  * @constructor
  1853.  */
  1854. function Checker() {
  1855. }
  1856. Checker.prototype = {
  1857.   /**
  1858.    * The XMLHttpRequest object that performs the connection.
  1859.    */
  1860.   _request  : null,
  1861.  
  1862.   /**
  1863.    * The nsIUpdateCheckListener callback
  1864.    */
  1865.   _callback : null,
  1866.  
  1867.   /**
  1868.    * The URL of the update service XML file to connect to that contains details
  1869.    * about available updates.
  1870.    */
  1871.   getUpdateURL: function(force) {
  1872.     this._forced = force;
  1873.  
  1874.     var defaults =
  1875.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1876.         getDefaultBranch(null);
  1877.  
  1878.     // Use the override URL if specified.
  1879.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1880.  
  1881.     // Otherwise, construct the update URL from component parts.
  1882.     if (!url) {
  1883.       try {
  1884.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1885.       } catch (e) {
  1886.       }
  1887.     }
  1888.  
  1889.     if (!url || url == "") {
  1890.       LOG("Checker", "Update URL not defined");
  1891.       return null;
  1892.     }
  1893.  
  1894.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1895.     url = url.replace(/%VERSION%/g, gApp.version);
  1896.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1897.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  1898.     url = url.replace(/%OS_VERSION%/g, gOSVersion);
  1899.     url = url.replace(/%LOCALE%/g, getLocale());
  1900.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1901.     url = url.replace(/%PLATFORM_VERSION%/g, gApp.platformVersion);
  1902.     url = url.replace(/%DISTRIBUTION%/g,
  1903.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION));
  1904.     url = url.replace(/%DISTRIBUTION_VERSION%/g,
  1905.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION_VERSION));
  1906.     url = url.replace(/\+/g, "%2B");
  1907.  
  1908.     if (force)
  1909.     url += "?force=1"
  1910.  
  1911.     LOG("Checker", "update url: " + url);
  1912.     return url;
  1913.   },
  1914.  
  1915.   /**
  1916.    * See nsIUpdateService.idl
  1917.    */
  1918.   checkForUpdates: function(listener, force) {
  1919.     if (!listener)
  1920.       throw Components.results.NS_ERROR_NULL_POINTER;
  1921.  
  1922.     if (!this.getUpdateURL(force) || (!this.enabled && !force))
  1923.       return;
  1924.  
  1925.     this._request =
  1926.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1927.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1928.     this._request.open("GET", this.getUpdateURL(force), true);
  1929.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1930.     this._request.overrideMimeType("text/xml");
  1931.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1932.  
  1933.     var self = this;
  1934.     this._request.onerror     = function(event) { self.onError(event);    };
  1935.     this._request.onload      = function(event) { self.onLoad(event);     };
  1936.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1937.  
  1938.     LOG("Checker", "checkForUpdates: sending request to " + this.getUpdateURL(force));
  1939.     this._request.send(null);
  1940.  
  1941.     this._callback = listener;
  1942.   },
  1943.  
  1944.   /**
  1945.    * When progress associated with the XMLHttpRequest is received.
  1946.    * @param   event
  1947.    *          The nsIDOMLSProgressEvent for the load.
  1948.    */
  1949.   onProgress: function(event) {
  1950.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1951.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1952.   },
  1953.  
  1954.   /**
  1955.    * Returns an array of nsIUpdate objects discovered by the update check.
  1956.    */
  1957.   get _updates() {
  1958.     var updatesElement = this._request.responseXML.documentElement;
  1959.     if (!updatesElement) {
  1960.       LOG("Checker", "get_updates: empty updates document?!");
  1961.       return [];
  1962.     }
  1963.  
  1964.     if (updatesElement.nodeName != "updates") {
  1965.       LOG("Checker", "get_updates: unexpected node name!");
  1966.       throw "";
  1967.     }
  1968.  
  1969.     var updates = [];
  1970.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  1971.       var updateElement = updatesElement.childNodes.item(i);
  1972.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1973.           updateElement.localName != "update")
  1974.         continue;
  1975.  
  1976.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1977.       try {
  1978.         var update = new Update(updateElement);
  1979.       } catch (e) {
  1980.         LOG("Checker", "Invalid <update/>, ignoring...");
  1981.         continue;
  1982.       }
  1983.       update.serviceURL = this.getUpdateURL(this._forced);
  1984.       update.channel = getUpdateChannel();
  1985.       updates.push(update);
  1986.     }
  1987.  
  1988.     return updates;
  1989.   },
  1990.  
  1991.   /**
  1992.    * The XMLHttpRequest succeeded and the document was loaded.
  1993.    * @param   event
  1994.    *          The nsIDOMLSEvent for the load
  1995.    */
  1996.   onLoad: function(event) {
  1997.     LOG("Checker", "onLoad: request completed downloading document");
  1998.  
  1999.     try {
  2000.       checkCert(this._request.channel);
  2001.  
  2002.       // Analyze the resulting DOM and determine the set of updates to install
  2003.       var updates = this._updates;
  2004.  
  2005.       LOG("Checker", "Updates available: " + updates.length);
  2006.  
  2007.       // ... and tell the Update Service about what we discovered.
  2008.       this._callback.onCheckComplete(event.target, updates, updates.length);
  2009.     }
  2010.     catch (e) {
  2011.       LOG("Checker", "There was a problem with the update service URL specified, " +
  2012.           "either the XML file was malformed or it does not exist at the location " +
  2013.           "specified. Exception: " + e);
  2014.       var update = new Update(null);
  2015.       update.statusText = getStatusTextFromCode(404, 404);
  2016.       this._callback.onError(event.target, update);
  2017.     }
  2018.  
  2019.     this._request = null;
  2020.   },
  2021.  
  2022.   /**
  2023.    * There was an error of some kind during the XMLHttpRequest
  2024.    * @param   event
  2025.    *          The nsIDOMLSEvent for the load
  2026.    */
  2027.   onError: function(event) {
  2028.     LOG("Checker", "onError: error during load");
  2029.  
  2030.     var request = event.target;
  2031.     try {
  2032.       var status = request.status;
  2033.     }
  2034.     catch (e) {
  2035.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  2036.       status = req.status;
  2037.     }
  2038.  
  2039.     // If we can't find an error string specific to this status code,
  2040.     // just use the 200 message from above, which means everything
  2041.     // "looks" fine but there was probably an XML error or a bogus file.
  2042.     var update = new Update(null);
  2043.     update.statusText = getStatusTextFromCode(status, 200);
  2044.     this._callback.onError(request, update);
  2045.  
  2046.     this._request = null;
  2047.   },
  2048.  
  2049.   /**
  2050.    * Whether or not we are allowed to do update checking.
  2051.    */
  2052.   _enabled: true,
  2053.  
  2054.   /**
  2055.    * See nsIUpdateService.idl
  2056.    */
  2057.   get enabled() {
  2058.     var aus =
  2059.         Components.classes["@mozilla.org/updates/update-service;1"].
  2060.         getService(Components.interfaces.nsIApplicationUpdateService);
  2061.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) &&
  2062.                   aus.canUpdate && this._enabled;
  2063.     return enabled;
  2064.   },
  2065.  
  2066.   /**
  2067.    * See nsIUpdateService.idl
  2068.    */
  2069.   stopChecking: function(duration) {
  2070.     // Always stop the current check
  2071.     if (this._request)
  2072.       this._request.abort();
  2073.  
  2074.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  2075.     switch (duration) {
  2076.     case nsIUpdateChecker.CURRENT_SESSION:
  2077.       this._enabled = false;
  2078.       break;
  2079.     case nsIUpdateChecker.ANY_CHECKS:
  2080.       this._enabled = false;
  2081.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  2082.       break;
  2083.     }
  2084.   },
  2085.  
  2086.   /**
  2087.    * See nsISupports.idl
  2088.    */
  2089.   QueryInterface: function(iid) {
  2090.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  2091.         !iid.equals(Components.interfaces.nsISupports))
  2092.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2093.     return this;
  2094.   }
  2095. };
  2096.  
  2097. /**
  2098.  * Manages the download of updates
  2099.  * @param   background
  2100.  *          Whether or not this downloader is operating in background
  2101.  *          update mode.
  2102.  * @constructor
  2103.  */
  2104. function Downloader(background) {
  2105.   this.background = background;
  2106. }
  2107. Downloader.prototype = {
  2108.   /**
  2109.    * The nsIUpdatePatch that we are downloading
  2110.    */
  2111.   _patch: null,
  2112.  
  2113.   /**
  2114.    * The nsIUpdate that we are downloading
  2115.    */
  2116.   _update: null,
  2117.  
  2118.   /**
  2119.    * The nsIIncrementalDownload object handling the download
  2120.    */
  2121.   _request: null,
  2122.  
  2123.   /**
  2124.    * Whether or not the update being downloaded is a complete replacement of
  2125.    * the user's existing installation or a patch representing the difference
  2126.    * between the new version and the previous version.
  2127.    */
  2128.   isCompleteUpdate: null,
  2129.  
  2130.   /**
  2131.    * Cancels the active download.
  2132.    */
  2133.   cancel: function() {
  2134.     if (this._request &&
  2135.         this._request instanceof Components.interfaces.nsIRequest) {
  2136.       const NS_BINDING_ABORTED = 0x804b0002;
  2137.       this._request.cancel(NS_BINDING_ABORTED);
  2138.     }
  2139.   },
  2140.  
  2141.   /**
  2142.    * Whether or not a patch has been downloaded and staged for installation.
  2143.    */
  2144.   get patchIsStaged() {
  2145.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  2146.   },
  2147.  
  2148.   /**
  2149.    * Verify the downloaded file.  We assume that the download is complete at
  2150.    * this point.
  2151.    */
  2152.   _verifyDownload: function() {
  2153.     if (!this._request)
  2154.       return false;
  2155.  
  2156.     var destination = this._request.destination;
  2157.  
  2158.     // Ensure that the file size matches the expected file size.
  2159.     if (destination.fileSize != this._patch.size)
  2160.       return false;
  2161.  
  2162.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  2163.         createInstance(nsIFileInputStream);
  2164.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2165.  
  2166.     try {
  2167.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  2168.           createInstance(nsICryptoHash);
  2169.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2170.       if (hashFunction == undefined)
  2171.         throw Components.results.NS_ERROR_UNEXPECTED;
  2172.       hash.init(hashFunction);
  2173.       hash.updateFromStream(fileStream, -1);
  2174.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2175.       // encoded binary (such as what is typically output by programs like
  2176.       // sha1sum).  In the future, this may change to base64 depending on how
  2177.       // we choose to compute these hashes.
  2178.       digest = binaryToHex(hash.finish(false));
  2179.     } catch (e) {
  2180.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  2181.       digest = "";
  2182.     }
  2183.  
  2184.     fileStream.close();
  2185.  
  2186.     return digest == this._patch.hashValue.toLowerCase();
  2187.   },
  2188.  
  2189.   /**
  2190.    * Select the patch to use given the current state of updateDir and the given
  2191.    * set of update patches.
  2192.    * @param   update
  2193.    *          A nsIUpdate object to select a patch from
  2194.    * @param   updateDir
  2195.    *          A nsIFile representing the update directory
  2196.    * @returns A nsIUpdatePatch object to download
  2197.    */
  2198.   _selectPatch: function(update, updateDir) {
  2199.     // Given an update to download, we will always try to download the patch
  2200.     // for a partial update over the patch for a full update.
  2201.  
  2202.     /**
  2203.      * Return the first UpdatePatch with the given type.
  2204.      * @param   type
  2205.      *          The type of the patch ("complete" or "partial")
  2206.      * @returns A nsIUpdatePatch object matching the type specified
  2207.      */
  2208.     function getPatchOfType(type) {
  2209.       for (var i = 0; i < update.patchCount; ++i) {
  2210.         var patch = update.getPatchAt(i);
  2211.         if (patch && patch.type == type)
  2212.           return patch;
  2213.       }
  2214.       return null;
  2215.     }
  2216.  
  2217.     // Look to see if any of the patches in the Update object has been
  2218.     // pre-selected for download, otherwise we must figure out which one
  2219.     // to select ourselves.
  2220.     var selectedPatch = update.selectedPatch;
  2221.  
  2222.     var state = readStatusFile(updateDir);
  2223.  
  2224.     // If this is a patch that we know about, then select it.  If it is a patch
  2225.     // that we do not know about, then remove it and use our default logic.
  2226.     var useComplete = false;
  2227.     if (selectedPatch) {
  2228.       LOG("Downloader", "found existing patch [state="+state+"]");
  2229.       switch (state) {
  2230.       case STATE_DOWNLOADING:
  2231.         LOG("Downloader", "resuming download");
  2232.         return selectedPatch;
  2233.       case STATE_PENDING:
  2234.         LOG("Downloader", "already downloaded and staged");
  2235.         return null;
  2236.       default:
  2237.         // Something went wrong when we tried to apply the previous patch.
  2238.         // Try the complete patch next time.
  2239.         if (update && selectedPatch.type == "partial") {
  2240.           useComplete = true;
  2241.         } else {
  2242.           // This is a pretty fatal error.  Just bail.
  2243.           LOG("Downloader", "failed to apply complete patch!");
  2244.           writeStatusFile(updateDir, STATE_NONE);
  2245.           return null;
  2246.         }
  2247.       }
  2248.  
  2249.       selectedPatch = null;
  2250.     }
  2251.  
  2252.     // If we were not able to discover an update from a previous download, we
  2253.     // select the best patch from the given set.
  2254.     var partialPatch = getPatchOfType("partial");
  2255.     if (!useComplete)
  2256.       selectedPatch = partialPatch;
  2257.     if (!selectedPatch) {
  2258.       if (partialPatch)
  2259.         partialPatch.selected = false;
  2260.       selectedPatch = getPatchOfType("complete");
  2261.     }
  2262.  
  2263.     // Restore the updateDir since we may have deleted it.
  2264.     updateDir = getUpdatesDir();
  2265.  
  2266.     // if update only contains a partial patch, selectedPatch == null here if
  2267.     // the partial patch has been attempted and fails and we're trying to get a
  2268.     // complete patch
  2269.     if (selectedPatch)
  2270.       selectedPatch.selected = true;
  2271.  
  2272.     update.isCompleteUpdate = useComplete;
  2273.  
  2274.     // Reset the Active Update object on the Update Manager and flush the
  2275.     // Active Update DB.
  2276.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2277.                        .getService(Components.interfaces.nsIUpdateManager);
  2278.     um.activeUpdate = update;
  2279.  
  2280.     return selectedPatch;
  2281.   },
  2282.  
  2283.   /**
  2284.    * Whether or not we are currently downloading something.
  2285.    */
  2286.   get isBusy() {
  2287.     return this._request != null;
  2288.   },
  2289.  
  2290.   /**
  2291.    * Download and stage the given update.
  2292.    * @param   update
  2293.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2294.    */
  2295.   downloadUpdate: function(update) {
  2296.     if (!update)
  2297.       throw Components.results.NS_ERROR_NULL_POINTER;
  2298.  
  2299.     var updateDir = getUpdatesDir();
  2300.  
  2301.     this._update = update;
  2302.  
  2303.     // This function may return null, which indicates that there are no patches
  2304.     // to download.
  2305.     this._patch = this._selectPatch(update, updateDir);
  2306.     if (!this._patch) {
  2307.       LOG("Downloader", "no patch to download");
  2308.       return readStatusFile(updateDir);
  2309.     }
  2310.     this.isCompleteUpdate = this._patch.type == "complete";
  2311.  
  2312.     var patchFile = updateDir.clone();
  2313.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2314.  
  2315.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2316.         getService(Components.interfaces.nsIIOService);
  2317.     var uri = ios.newURI(this._patch.URL, null, null);
  2318.  
  2319.     this._request =
  2320.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2321.         createInstance(nsIIncrementalDownload);
  2322.  
  2323.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " +
  2324.         patchFile.path);
  2325.  
  2326.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2327.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2328.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2329.     this._request.start(this, null);
  2330.  
  2331.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2332.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2333.     this._patch.state = STATE_DOWNLOADING;
  2334.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2335.                        .getService(Components.interfaces.nsIUpdateManager);
  2336.     um.saveUpdates();
  2337.     return STATE_DOWNLOADING;
  2338.   },
  2339.  
  2340.   /**
  2341.    * An array of download listeners to notify when we receive
  2342.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2343.    */
  2344.   _listeners: [],
  2345.  
  2346.   /**
  2347.    * Adds a listener to the download process
  2348.    * @param   listener
  2349.    *          A download listener, implementing nsIRequestObserver and
  2350.    *          nsIProgressEventSink
  2351.    */
  2352.   addDownloadListener: function(listener) {
  2353.     for (var i = 0; i < this._listeners.length; ++i) {
  2354.       if (this._listeners[i] == listener)
  2355.         return;
  2356.     }
  2357.     this._listeners.push(listener);
  2358.   },
  2359.  
  2360.   /**
  2361.    * Removes a download listener
  2362.    * @param   listener
  2363.    *          The listener to remove.
  2364.    */
  2365.   removeDownloadListener: function(listener) {
  2366.     for (var i = 0; i < this._listeners.length; ++i) {
  2367.       if (this._listeners[i] == listener) {
  2368.         this._listeners.splice(i, 1);
  2369.         return;
  2370.       }
  2371.     }
  2372.   },
  2373.  
  2374.   /**
  2375.    * When the async request begins
  2376.    * @param   request
  2377.    *          The nsIRequest object for the transfer
  2378.    * @param   context
  2379.    *          Additional data
  2380.    */
  2381.   onStartRequest: function(request, context) {
  2382.     request.QueryInterface(nsIIncrementalDownload);
  2383.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2384.  
  2385.     var listenerCount = this._listeners.length;
  2386.     for (var i = 0; i < listenerCount; ++i)
  2387.       this._listeners[i].onStartRequest(request, context);
  2388.   },
  2389.  
  2390.   /**
  2391.    * When new data has been downloaded
  2392.    * @param   request
  2393.    *          The nsIRequest object for the transfer
  2394.    * @param   context
  2395.    *          Additional data
  2396.    * @param   progress
  2397.    *          The current number of bytes transferred
  2398.    * @param   maxProgress
  2399.    *          The total number of bytes that must be transferred
  2400.    */
  2401.   onProgress: function(request, context, progress, maxProgress) {
  2402.     request.QueryInterface(nsIIncrementalDownload);
  2403.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2404.  
  2405.     var listenerCount = this._listeners.length;
  2406.     for (var i = 0; i < listenerCount; ++i) {
  2407.       var listener = this._listeners[i];
  2408.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2409.         listener.onProgress(request, context, progress, maxProgress);
  2410.     }
  2411.   },
  2412.  
  2413.   /**
  2414.    * When we have new status text
  2415.    * @param   request
  2416.    *          The nsIRequest object for the transfer
  2417.    * @param   context
  2418.    *          Additional data
  2419.    * @param   status
  2420.    *          A status code
  2421.    * @param   statusText
  2422.    *          Human readable version of |status|
  2423.    */
  2424.   onStatus: function(request, context, status, statusText) {
  2425.     request.QueryInterface(nsIIncrementalDownload);
  2426.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2427.     var listenerCount = this._listeners.length;
  2428.     for (var i = 0; i < listenerCount; ++i) {
  2429.       var listener = this._listeners[i];
  2430.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2431.         listener.onStatus(request, context, status, statusText);
  2432.     }
  2433.   },
  2434.  
  2435.   /**
  2436.    * When data transfer ceases
  2437.    * @param   request
  2438.    *          The nsIRequest object for the transfer
  2439.    * @param   context
  2440.    *          Additional data
  2441.    * @param   status
  2442.    *          Status code containing the reason for the cessation.
  2443.    */
  2444.   onStopRequest: function(request, context, status) {
  2445.     request.QueryInterface(nsIIncrementalDownload);
  2446.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2447.  
  2448.     var state = this._patch.state;
  2449.     var shouldShowPrompt = false;
  2450.     var deleteActiveUpdate = false;
  2451.     const NS_BINDING_ABORTED = 0x804b0002;
  2452.     const NS_ERROR_ABORT = 0x80004004;
  2453.     if (Components.isSuccessCode(status)) {
  2454.       var sbs =
  2455.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  2456.           getService(Components.interfaces.nsIStringBundleService);
  2457.       var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2458.       if (this._verifyDownload()) {
  2459.         state = STATE_PENDING;
  2460.  
  2461.         // We only need to explicitly show the prompt if this is a backround
  2462.         // download, since otherwise some kind of UI is already visible and
  2463.         // that UI will notify.
  2464.         if (this.background)
  2465.           shouldShowPrompt = true;
  2466.  
  2467.         // Tell the updater.exe we're ready to apply.
  2468.         writeStatusFile(getUpdatesDir(), state);
  2469.         this._update.installDate = (new Date()).getTime();
  2470.         this._update.statusText = updateStrings.
  2471.           GetStringFromName("installPending");
  2472.       } else {
  2473.         LOG("Downloader", "onStopRequest: download verification failed");
  2474.         state = STATE_DOWNLOAD_FAILED;
  2475.  
  2476.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2477.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2478.         this._update.statusText = updateStrings.
  2479.           formatStringFromName("verificationError", [brandShortName], 1);
  2480.  
  2481.         // TODO: use more informative error code here
  2482.         status = Components.results.NS_ERROR_UNEXPECTED;
  2483.  
  2484.         var message = getStatusTextFromCode("verification_failed",
  2485.           "verification_failed");
  2486.         this._update.statusText = message;
  2487.  
  2488.         if (this._update.isCompleteUpdate)
  2489.           deleteActiveUpdate = true;
  2490.  
  2491.         // Destroy the updates directory, since we're done with it.
  2492.         cleanUpUpdatesDir();
  2493.       }
  2494.     }
  2495.     else if (status != NS_BINDING_ABORTED &&
  2496.              status != NS_ERROR_ABORT) {
  2497.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2498.       // Some sort of other failure, log this in the |statusText| property
  2499.       state = STATE_DOWNLOAD_FAILED;
  2500.  
  2501.       // XXXben - if |request| (The Incremental Download) provided a means
  2502.       // for accessing the http channel we could do more here.
  2503.  
  2504.       const NS_BINDING_FAILED = 2152398849;
  2505.       this._update.statusText = getStatusTextFromCode(status,
  2506.         NS_BINDING_FAILED);
  2507.  
  2508.       // Destroy the updates directory, since we're done with it.
  2509.       cleanUpUpdatesDir();
  2510.  
  2511.       deleteActiveUpdate = true;
  2512.     }
  2513.     LOG("Downloader", "Setting state to: " + state);
  2514.     this._patch.state = state;
  2515.     var um =
  2516.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2517.         getService(Components.interfaces.nsIUpdateManager);
  2518.     if (deleteActiveUpdate) {
  2519.       this._update.installDate = (new Date()).getTime();
  2520.       um.activeUpdate = null;
  2521.     }
  2522.     um.saveUpdates();
  2523.  
  2524.     var listenerCount = this._listeners.length;
  2525.     for (var i = 0; i < listenerCount; ++i)
  2526.       this._listeners[i].onStopRequest(request, context, status);
  2527.  
  2528.     this._request = null;
  2529.  
  2530.     if (state == STATE_DOWNLOAD_FAILED) {
  2531.       if (!this._update.isCompleteUpdate) {
  2532.         var allFailed = true;
  2533.  
  2534.         // If we were downloading a patch and the patch verification phase
  2535.         // failed, log this and then commence downloading the complete update.
  2536.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2537.         this._update.isCompleteUpdate = true;
  2538.         var status = this.downloadUpdate(this._update);
  2539.  
  2540.         if (status == STATE_NONE) {
  2541.           cleanupActiveUpdate();
  2542.         } else {
  2543.           allFailed = false;
  2544.         }
  2545.         // This will reset the |.state| property on this._update if a new
  2546.         // download initiates.
  2547.       }
  2548.  
  2549.       // if we still fail after trying a complete download, give up completely
  2550.       if (allFailed) {
  2551.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2552.         // ...
  2553.  
  2554.         // If this was ever a foreground download, and now there is no UI active
  2555.         // (e.g. because the user closed the download window) and there was an
  2556.         // error, we must notify now. Otherwise we can keep the failure to
  2557.         // ourselves since the user won't be expecting it.
  2558.         try {
  2559.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2560.           var fgdl = this._update.getProperty("foregroundDownload");
  2561.         }
  2562.         catch (e) {
  2563.         }
  2564.  
  2565.         if (fgdl == "true") {
  2566.           var prompter =
  2567.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2568.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2569.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2570.           this._update.setProperty("downloadFailed", "true");
  2571.           prompter.showUpdateError(this._update);
  2572.         }
  2573.       }
  2574.  
  2575.       // the complete download succeeded or total failure was handled, so exit
  2576.       return;
  2577.     }
  2578.  
  2579.     // Do this after *everything* else, since it will likely cause the app
  2580.     // to shut down.
  2581.     if (shouldShowPrompt) {
  2582.       // Notify the user that an update has been downloaded and is ready for
  2583.       // installation (i.e. that they should restart the application). We do
  2584.       // not notify on failed update attempts.
  2585.       var prompter =
  2586.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2587.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2588.       prompter.showUpdateDownloaded(this._update, true);
  2589.     }
  2590.   },
  2591.  
  2592.   /**
  2593.    * See nsIInterfaceRequestor.idl
  2594.    */
  2595.   getInterface: function(iid) {
  2596.     // The network request may require proxy authentication, so provide the
  2597.     // default nsIAuthPrompt if requested.
  2598.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2599.       var prompt =
  2600.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2601.           createInstance();
  2602.       return prompt.QueryInterface(iid);
  2603.     }
  2604.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2605.   },
  2606.  
  2607.   /**
  2608.    * See nsISupports.idl
  2609.    */
  2610.   QueryInterface: function(iid) {
  2611.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2612.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2613.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2614.         !iid.equals(Components.interfaces.nsISupports))
  2615.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2616.     return this;
  2617.   }
  2618. };
  2619.  
  2620. /**
  2621.  * A manager for update check timers. Manages timers that fire over long
  2622.  * periods of time (e.g. days, weeks).
  2623.  * @constructor
  2624.  */
  2625. function TimerManager() {
  2626.   getObserverService().addObserver(this, "xpcom-shutdown", false);
  2627.  
  2628.   const nsITimer = Components.interfaces.nsITimer;
  2629.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2630.                           .createInstance(nsITimer);
  2631.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2632.   this._timer.initWithCallback(this, timerInterval,
  2633.                                nsITimer.TYPE_REPEATING_SLACK);
  2634. }
  2635. TimerManager.prototype = {
  2636.   /**
  2637.    * See nsIObserver.idl
  2638.    */
  2639.   observe: function(subject, topic, data) {
  2640.     if (topic == "xpcom-shutdown") {
  2641.      getObserverService().removeObserver(this, "xpcom-shutdown");
  2642.  
  2643.       // Release everything we hold onto.
  2644.       for (var timerID in this._timers)
  2645.         delete this._timers[timerID];
  2646.       this._timer = null;
  2647.       this._timers = null;
  2648.     }
  2649.   },
  2650.  
  2651.   /**
  2652.    * The Checker Timer
  2653.    */
  2654.   _timer: null,
  2655.  
  2656.   /**
  2657.    * The set of registered timers.
  2658.    */
  2659.   _timers: { },
  2660.  
  2661.   /**
  2662.    * Called when the checking timer fires.
  2663.    * @param   timer
  2664.    *          The checking timer that fired.
  2665.    */
  2666.   notify: function(timer) {
  2667.     for (var timerID in this._timers) {
  2668.       var timerData = this._timers[timerID];
  2669.       var lastUpdateTime = timerData.lastUpdateTime;
  2670.       var now = Math.round(Date.now() / 1000);
  2671.  
  2672.       // Fudge the lastUpdateTime by some random increment of the update
  2673.       // check interval (e.g. some random slice of 10 minutes) so that when
  2674.       // the time comes to check, we offset each client request by a random
  2675.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2676.       // whereas app.update.lastUpdateTime is in seconds
  2677.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2678.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2679.  
  2680.       if ((now - lastUpdateTime) > timerData.interval &&
  2681.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2682.         timerData.callback.notify(timer);
  2683.         timerData.lastUpdateTime = now;
  2684.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2685.         gPref.setIntPref(preference, now);
  2686.       }
  2687.     }
  2688.   },
  2689.  
  2690.   /**
  2691.    * See nsIUpdateService.idl
  2692.    */
  2693.   registerTimer: function(id, callback, interval) {
  2694.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2695.     var now = Math.round(Date.now() / 1000);
  2696.     var lastUpdateTime = null;
  2697.     if (gPref.prefHasUserValue(preference)) {
  2698.       lastUpdateTime = gPref.getIntPref(preference);
  2699.     } else {
  2700.       gPref.setIntPref(preference, now);
  2701.       lastUpdateTime = now;
  2702.     }
  2703.     this._timers[id] = { callback       : callback,
  2704.                          interval       : interval,
  2705.                          lastUpdateTime : lastUpdateTime };
  2706.   },
  2707.  
  2708.   /**
  2709.    * See nsISupports.idl
  2710.    */
  2711.   QueryInterface: function(iid) {
  2712.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2713.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2714.         !iid.equals(Components.interfaces.nsIObserver) &&
  2715.         !iid.equals(Components.interfaces.nsISupports))
  2716.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2717.     return this;
  2718.   }
  2719. };
  2720.  
  2721. //@line 2817 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2722. /**
  2723.  * UpdatePrompt
  2724.  * An object which can prompt the user with information about updates, request
  2725.  * action, etc. Embedding clients can override this component with one that
  2726.  * invokes a native front end.
  2727.  * @constructor
  2728.  */
  2729. function UpdatePrompt() {
  2730. }
  2731. UpdatePrompt.prototype = {
  2732.   /**
  2733.    * See nsIUpdateService.idl
  2734.    */
  2735.   checkForUpdates: function() {
  2736.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2737.                  null, null);
  2738.   },
  2739.  
  2740.   /**
  2741.    * See nsIUpdateService.idl
  2742.    */
  2743.   showUpdateAvailable: function(update) {
  2744.     if (!this._enabled)
  2745.       return;
  2746.     var bundle = this._updateBundle;
  2747.     var stringsPrefix = "updateAvailable_" + update.type + ".";
  2748.     var title = bundle.formatStringFromName(stringsPrefix + "title", [update.name], 1);
  2749.     var text = bundle.GetStringFromName(stringsPrefix + "text");
  2750.     var imageUrl = "";
  2751.     this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2752.                            "Update:Wizard", "updatesavailable", update,
  2753.                            title, text, imageUrl);
  2754.   },
  2755.  
  2756.   /**
  2757.    * See nsIUpdateService.idl
  2758.    */
  2759.   showUpdateDownloaded: function(update, background) {
  2760.     if (background) {
  2761.       if (!this._enabled)
  2762.         return;
  2763.       var bundle = this._updateBundle;
  2764.       var stringsPrefix = "updateDownloaded_" + update.type + ".";
  2765.       var title = bundle.formatStringFromName(stringsPrefix + "title", [update.name], 1);
  2766.       var text = bundle.GetStringFromName(stringsPrefix + "text");
  2767.       var imageUrl = "";
  2768.       this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2769.                               "Update:Wizard", "finishedBackground", update,
  2770.                               title, text, imageUrl);
  2771.     } else {
  2772.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2773.                    "Update:Wizard", "finishedBackground", update);
  2774.     }
  2775.   },
  2776.  
  2777.   /**
  2778.    * See nsIUpdateService.idl
  2779.    */
  2780.   showUpdateInstalled: function(update) {
  2781.     var showUpdateInstalledUI = getPref("getBoolPref",
  2782.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2783.     if (this._enabled && showUpdateInstalledUI) {
  2784.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2785.                    "installed", update);
  2786.     }
  2787.   },
  2788.  
  2789.   /**
  2790.    * See nsIUpdateService.idl
  2791.    */
  2792.   showUpdateError: function(update) {
  2793.     if (this._enabled) {
  2794.       // In some cases, we want to just show a simple alert dialog:
  2795.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2796.         var updateBundle = this._updateBundle;
  2797.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2798.         var text = updateBundle.formatStringFromName("updaterIOErrorMsg",
  2799.                                                      [gApp.name, gApp.name], 2);
  2800.         var ww =
  2801.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2802.             getService(Components.interfaces.nsIWindowWatcher);
  2803.         ww.getNewPrompter(null).alert(title, text);
  2804.       } else {
  2805.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2806.                      "errors", update);
  2807.       }
  2808.     }
  2809.   },
  2810.  
  2811.   /**
  2812.    * See nsIUpdateService.idl
  2813.    */
  2814.   showUpdateHistory: function(parent) {
  2815.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History",
  2816.                  null, null);
  2817.   },
  2818.  
  2819.   /**
  2820.    * Whether or not we are enabled (i.e. not in Silent mode)
  2821.    */
  2822.   get _enabled() {
  2823.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2824.   },
  2825.  
  2826.   get _updateBundle() {
  2827.     return Components.classes["@mozilla.org/intl/stringbundle;1"]
  2828.                      .getService(Components.interfaces.nsIStringBundleService)
  2829.                      .createBundle(URI_UPDATES_PROPERTIES);
  2830.   },
  2831.  
  2832.   /**
  2833.    * Initiate a less obtrusive UI, starting with a non-modal notification alert
  2834.    * @param   parent
  2835.    *          A parent window, can be null
  2836.    * @param   uri
  2837.    *          The URI string of the dialog to show
  2838.    * @param   name
  2839.    *          The Window Name of the dialog to show, in case it is already open
  2840.    *          and can merely be focused
  2841.    * @param   page
  2842.    *          The page of the wizard to be displayed, if one is already open.
  2843.    * @param   update
  2844.    *          An update to pass to the UI in the window arguments.
  2845.    *          Can be null
  2846.    * @param   title
  2847.    *          The title for the notification alert.
  2848.    * @param   text
  2849.    *          The contents of the notification alert.
  2850.    * @param   imageUrl
  2851.    *          A URL identifying the image to put in the notification alert.
  2852.    */
  2853.   _showUnobtrusiveUI: function(parent, uri, features, name, page, update,
  2854.                                title, text, imageUrl) {
  2855.     var observer = {
  2856.       updatePrompt: this,
  2857.       service: null,
  2858.       timer: null,
  2859.       notify: function () {
  2860.         // the user hasn't restarted yet => prompt when idle
  2861.         this.service.removeObserver(this, "quit-application");
  2862.         this.updatePrompt._showUIWhenIdle(parent, uri, features, name, page, update);
  2863.       },
  2864.       observe: function (aSubject, aTopic, aData) {
  2865.         switch (aTopic) {
  2866.           case "alertclickcallback":
  2867.             this.updatePrompt._showUI(parent, uri, features, name, page, update);
  2868.             // fall thru
  2869.           case "quit-application":
  2870.             this.timer.cancel();
  2871.             this.service.removeObserver(this, "quit-application");
  2872.             break;
  2873.         }
  2874.       }
  2875.     };
  2876.  
  2877.     try {
  2878.       var notifier = Components.classes["@mozilla.org/alerts-service;1"]
  2879.                                .getService(Components.interfaces.nsIAlertsService);
  2880.       notifier.showAlertNotification(imageUrl, title, text, true, "", observer);
  2881.     }
  2882.     catch (e) {
  2883.       // Failed to retrieve alerts service, platform unsupported
  2884.       this._showUIWhenIdle(parent, uri, features, name, page, update);
  2885.       return;
  2886.     }
  2887.  
  2888.     observer.service =
  2889.       Components.classes["@mozilla.org/observer-service;1"]
  2890.                 .getService(Components.interfaces.nsIObserverService);
  2891.     observer.service.addObserver(observer, "quit-application", false);
  2892.  
  2893.     // Give the user x seconds to react before showing the big UI
  2894.     var promptWaitTime = getPref("getIntPref", PREF_APP_UPDATE_PROMPTWAITTIME, 43200);
  2895.     observer.timer =
  2896.       Components.classes["@mozilla.org/timer;1"]
  2897.                 .createInstance(Components.interfaces.nsITimer);
  2898.     observer.timer.initWithCallback(observer, promptWaitTime * 1000,
  2899.                                     observer.timer.TYPE_ONE_SHOT);
  2900.   },
  2901.  
  2902.   /**
  2903.    * Show the UI when the user was idle
  2904.    * @param   parent
  2905.    *          A parent window, can be null
  2906.    * @param   uri
  2907.    *          The URI string of the dialog to show
  2908.    * @param   name
  2909.    *          The Window Name of the dialog to show, in case it is already open
  2910.    *          and can merely be focused
  2911.    * @param   page
  2912.    *          The page of the wizard to be displayed, if one is already open.
  2913.    * @param   update
  2914.    *          An update to pass to the UI in the window arguments.
  2915.    *          Can be null
  2916.    */
  2917.   _showUIWhenIdle: function(parent, uri, features, name, page, update) {
  2918.     var idleService =
  2919.       Components.classes["@mozilla.org/widget/idleservice;1"]
  2920.                 .getService(Components.interfaces.nsIIdleService);
  2921.  
  2922.     const IDLE_TIME = getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60);
  2923.     if (idleService.idleTime / 1000 >= IDLE_TIME) {
  2924.       this._showUI(parent, uri, features, name, page, update);
  2925.     } else {
  2926.       var observerService =
  2927.         Components.classes["@mozilla.org/observer-service;1"]
  2928.                   .getService(Components.interfaces.nsIObserverService);
  2929.       var observer = {
  2930.         updatePrompt: this,
  2931.         observe: function (aSubject, aTopic, aData) {
  2932.           switch (aTopic) {
  2933.             case "idle":
  2934.               this.updatePrompt._showUI(parent, uri, features, name, page, update);
  2935.               // fall thru
  2936.             case "quit-application":
  2937.               idleService.removeIdleObserver(this, IDLE_TIME);
  2938.               observerService.removeObserver(this, "quit-application");
  2939.               break;
  2940.           }
  2941.         }
  2942.       };
  2943.       idleService.addIdleObserver(observer, IDLE_TIME);
  2944.       observerService.addObserver(observer, "quit-application", false);
  2945.     }
  2946.   },
  2947.  
  2948.   /**
  2949.    * Show the Update Checking UI
  2950.    * @param   parent
  2951.    *          A parent window, can be null
  2952.    * @param   uri
  2953.    *          The URI string of the dialog to show
  2954.    * @param   name
  2955.    *          The Window Name of the dialog to show, in case it is already open
  2956.    *          and can merely be focused
  2957.    * @param   page
  2958.    *          The page of the wizard to be displayed, if one is already open.
  2959.    * @param   update
  2960.    *          An update to pass to the UI in the window arguments.
  2961.    *          Can be null
  2962.    */
  2963.   _showUI: function(parent, uri, features, name, page, update) {
  2964.     var ary = null;
  2965.     if (update) {
  2966.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2967.                       .createInstance(Components.interfaces.nsISupportsArray);
  2968.       ary.AppendElement(update);
  2969.     }
  2970.  
  2971.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  2972.                        .getService(Components.interfaces.nsIWindowMediator);
  2973.     var win = wm.getMostRecentWindow(name);
  2974.     if (win) {
  2975.       if (page && "setCurrentPage" in win)
  2976.         win.setCurrentPage(page);
  2977.       win.focus();
  2978.     }
  2979.     else {
  2980.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2981.       if (features)
  2982.         openFeatures += "," + features;
  2983.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2984.                          .getService(Components.interfaces.nsIWindowWatcher);
  2985.       ww.openWindow(parent, uri, "", openFeatures, ary);
  2986.     }
  2987.   },
  2988.  
  2989.   /**
  2990.    * See nsISupports.idl
  2991.    */
  2992.   QueryInterface: function(iid) {
  2993.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  2994.         !iid.equals(Components.interfaces.nsISupports))
  2995.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2996.     return this;
  2997.   }
  2998. };
  2999. //@line 3095 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3000.  
  3001. var gModule = {
  3002.   registerSelf: function(componentManager, fileSpec, location, type) {
  3003.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  3004.  
  3005.     for (var key in this._objects) {
  3006.       var obj = this._objects[key];
  3007.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  3008.                                                fileSpec, location, type);
  3009.     }
  3010.  
  3011.     // Make the Update Service a startup observer
  3012.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  3013.                                     .getService(Components.interfaces.nsICategoryManager);
  3014.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  3015.                                      "service," + this._objects.service.contractID,
  3016.                                      true, true);
  3017.   },
  3018.  
  3019.   getClassObject: function(componentManager, cid, iid) {
  3020.     if (!iid.equals(Components.interfaces.nsIFactory))
  3021.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  3022.  
  3023.     for (var key in this._objects) {
  3024.       if (cid.equals(this._objects[key].CID))
  3025.         return this._objects[key].factory;
  3026.     }
  3027.  
  3028.     throw Components.results.NS_ERROR_NO_INTERFACE;
  3029.   },
  3030.  
  3031.   _objects: {
  3032.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  3033.                contractID : "@mozilla.org/updates/update-service;1",
  3034.                className  : "Update Service",
  3035.                factory    : makeFactory(UpdateService)
  3036.              },
  3037.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  3038.                contractID : "@mozilla.org/updates/update-checker;1",
  3039.                className  : "Update Checker",
  3040.                factory    : makeFactory(Checker)
  3041.              },
  3042. //@line 3138 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3043.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  3044.                contractID : "@mozilla.org/updates/update-prompt;1",
  3045.                className  : "Update Prompt",
  3046.                factory    : makeFactory(UpdatePrompt)
  3047.              },
  3048. //@line 3144 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3049.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  3050.                contractID : "@mozilla.org/updates/timer-manager;1",
  3051.                className  : "Timer Manager",
  3052.                factory    : makeFactory(TimerManager)
  3053.              },
  3054.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  3055.                contractID : "@mozilla.org/updates/update-manager;1",
  3056.                className  : "Update Manager",
  3057.                factory    : makeFactory(UpdateManager)
  3058.              },
  3059.   },
  3060.  
  3061.   canUnload: function(componentManager) {
  3062.     return true;
  3063.   }
  3064. };
  3065.  
  3066. /**
  3067.  * Creates a factory for instances of an object created using the passed-in
  3068.  * constructor.
  3069.  */
  3070. function makeFactory(ctor) {
  3071.   function ci(outer, iid) {
  3072.     if (outer != null)
  3073.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  3074.     return (new ctor()).QueryInterface(iid);
  3075.   }
  3076.   return { createInstance: ci };
  3077. }
  3078.  
  3079. function NSGetModule(compMgr, fileSpec) {
  3080.   return gModule;
  3081. }
  3082.  
  3083. /**
  3084.  * Determines whether or there are installed addons which are incompatible
  3085.  * with this update.
  3086.  * @param   update
  3087.  *          The update to check compatibility against
  3088.  * @returns true if there are no addons installed that are incompatible with
  3089.  *          the specified update, false otherwise.
  3090.  */
  3091. function isCompatible(update) {
  3092. //@line 3188 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3093.   var em =
  3094.       Components.classes["@mozilla.org/extensions/manager;1"].
  3095.       getService(nsIExtensionManager);
  3096.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  3097.     update.platformVersion, nsIUpdateItem.TYPE_ANY, false, { });
  3098.   return items.length == 0;
  3099. //@line 3197 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3100. }
  3101.  
  3102. /**
  3103.  * Shows a prompt for an update, provided there are no incompatible addons.
  3104.  * If there are, kick off an update check and see if updates are available
  3105.  * that will resolve the incompatibilities.
  3106.  * @param   update
  3107.  *          The available update to show
  3108.  */
  3109. function showPromptIfNoIncompatibilities(update) {
  3110.   function showPrompt(update) {
  3111.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  3112.     var prompter =
  3113.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  3114.         createInstance(Components.interfaces.nsIUpdatePrompt);
  3115.     prompter.showUpdateAvailable(update);
  3116.   }
  3117.  
  3118. //@line 3216 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3119.   /**
  3120.    * Determines if an addon is compatible with a particular update.
  3121.    * @param   addon
  3122.    *          The addon to check
  3123.    * @param   version
  3124.    *          The extensionVersion of the update to check for compatibility
  3125.    *          against.
  3126.    * @returns true if the addon is compatible, false otherwise
  3127.    */
  3128.   function addonIsCompatible(addon, version) {
  3129.     var vc =
  3130.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  3131.         getService(Components.interfaces.nsIVersionComparator);
  3132.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  3133.            (vc.compare(version, addon.maxAppVersion) <= 0);
  3134.   }
  3135.  
  3136.   /**
  3137.    * An object implementing nsIAddonUpdateCheckListener that looks for
  3138.    * available updates to addons and if updates are found that will make the
  3139.    * user's installed addon set compatible with the update, suppresses the
  3140.    * prompt that would otherwise be shown.
  3141.    * @param   addons
  3142.    *          An array of incompatible addons that are installed.
  3143.    * @constructor
  3144.    */
  3145.   function Listener(addons) {
  3146.     this._addons = addons;
  3147.   }
  3148.   Listener.prototype = {
  3149.     _addons: null,
  3150.  
  3151.     /**
  3152.      * See nsIUpdateService.idl
  3153.      */
  3154.     onUpdateStarted: function() {
  3155.     },
  3156.     onUpdateEnded: function() {
  3157.       // There are still incompatibilities, even after an extension update
  3158.       // check to see if there were newer, compatible versions available, so
  3159.       // we have to prompt.
  3160.       //
  3161.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we
  3162.       // handle incompatibilities:
  3163.       // UPDATE_CHECK_NEWVERSION    We count both VersionInfo updates _and_
  3164.       //      NewerVersion updates against the list of incompatible addons
  3165.       //      installed - i.e. if Foo 1.2 is installed and it is incompatible
  3166.       //      with the update, and we find Foo 2.0 which is but which is not
  3167.       //      yet downloaded or installed, then we do NOT prompt because the
  3168.       //      user can download Foo 2.0 when they restart after the update
  3169.       //      during the mismatch checking UI. This is the default, since it
  3170.       //      suppresses most prompt dialogs.
  3171.       // UPDATE_CHECK_COMPATIBILITY    We count only VersionInfo updates
  3172.       //      against the list of incompatible addons installed - i.e. if the
  3173.       //      situation above with Foo 1.2 and available update to 2.0
  3174.       //      applies, we DO show the prompt since a download operation will
  3175.       //      be required after the update. This is not the default and is
  3176.       //      supplied only as a hidden option for those that want it.
  3177.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE,
  3178.                          nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  3179.       if ((mode == nsIExtensionManager.UPDATE_CHECK_NEWVERSION
  3180.            && this._addons.length) || !isCompatible(update))
  3181.         showPrompt(update);
  3182.     },
  3183.     onAddonUpdateStarted: function(addon) {
  3184.     },
  3185.     onAddonUpdateEnded: function(addon, status) {
  3186.       const Ci = Components.interfaces;
  3187.       if (status != Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE)
  3188.         return;
  3189.  
  3190.       var reqVersion = addon.targetAppID == TOOLKIT_ID ?
  3191.                        update.platformVersion :
  3192.                        update.extensionVersion;
  3193.       if (!addonIsCompatible(addon, reqVersion))
  3194.         return;
  3195.  
  3196.       for (var i = 0; i < this._addons.length; ++i) {
  3197.         if (this._addons[i] == addon) {
  3198.           this._addons.splice(i, 1);
  3199.           break;
  3200.         }
  3201.       }
  3202.     },
  3203.     /**
  3204.      * See nsISupports.idl
  3205.      */
  3206.     QueryInterface: function(iid) {
  3207.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  3208.           !iid.equals(Components.interfaces.nsISupports))
  3209.         throw Components.results.NS_ERROR_NO_INTERFACE;
  3210.       return this;
  3211.     }
  3212.   };
  3213.  
  3214.   if (!isCompatible(update)) {
  3215.     var em =
  3216.         Components.classes["@mozilla.org/extensions/manager;1"].
  3217.         getService(nsIExtensionManager);
  3218.     var items = em.getIncompatibleItemList("", update.extensionVersion,
  3219.       update.platformVersion, nsIUpdateItem.TYPE_ANY, false, { });
  3220.     var listener = new Listener(items);
  3221.     // See documentation on |mode| above.
  3222.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE,
  3223.                        nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  3224.     em.update([], 0, mode, listener);
  3225.   }
  3226.   else
  3227. //@line 3325 "/builds/tinderbox/Fx-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3228.     showPrompt(update);
  3229. }
  3230.